all SpotLights on/off c#,Spotlight on/off C#

how to turn on and off all spotlights on scen and How to make it just for one spotlight (ForEach c#)?

FindObjectsOfType(typeof(Light)) will return all active lights in the scene, and then it’s just a matter of iterating over all of them and checking if their type == LightType.Spot if you’re looking specifically for spotlights. Add them all to a collection and you can toggle them off and on as needed, but it’s worth noting that it doesn’t return inactive objects.

FindObjectsOfTypeAll(typeof(Light)) will grab all lights both in the scene and in prefabs in the Assets folder- it can be annoying having to sift through them just to find the scene lights, and it can be dangerous if you don’t bother filtering and accidentally change asset files. It’s also an extremely heavy operation in large scenes.

The best solution is to make a new collection of Light objects in a manager or singleton somewhere in the scene and manually drag each Light object into the collection in the inspector. This removes the need to use heavy Find functions- you can just iterate over the list when needed to enable/disable the light en-masse.

You can optionally make the collection hold object types that have int IDs, string Names, and the Light reference, instead of just the Light reference by itself, to be able to disable or enable specific lights by ID or Name.

public class LightManager : MonoBehaviour
{
    public class LightReference
    {
        public int id;
        public string name;
        public Light light;
    }

    public LightReference[] lightReferences;

    public void EnableAll()
    {
        foreach(var obj in lightReferences)
        {
            obj.light.enabled = true;
        }
    }
    // ETC...
}

You could also make a new MonoBehaviour for the ID/Name combo to put on the light objects themselves, then make a collection of that type on the manager. This has the added benefit of each object maintaining its own identity, which is a plus, but it depends on what your specific needs are.

Thanks. Why does this code not work for me?

Light[] lights = FindObjectsOfTypeAll (typeof(Light));

foreach(Light obj in lights)
{
    if (obj is LightType.Spot) {
        obj.enabled = true;
    }
}