- Home /
how can i write this properly
public streetLight GameObject.FindGameObjectsWithTag ("StreetLights");
i want to shut them all once so i need streetLight var with tagged
Answer by allenallenallen · Jan 26, 2016 at 10:41 PM
public GameObject[] streetLights; // This is an array of GameObjects
void Start(){
streetLights = GameObject.FindGameObjectsWithTag("StreetLights");
}
Remember to declare the type of the variable before you declare the name of it.
all right but i am taking this now
Assets/DayNightCycle01/Scripts/DayNightController.cs(81,38): error CS1061: Type UnityEngine.GameObject[]' does not contain a definition for
SetActive' and no extension method SetActive' of type
UnityEngine.GameObject[]' could be found (are you missing a using directive or an assembly reference?)
You need to loop through the array and set each gameobject to be SetActive(false).
foreach(var streetLight in streetLights)
{
streetLight.SetActive(false);
}
Answer by JoshuaMcKenzie · Jan 27, 2016 at 06:04 AM
You can use UnityEvents to handle this
using UnityEngine;
using UnityEvent.Events;
public class StreetLightScript: MonoBehaviour
{
public GameObject lightInChild;
public static UnityEvent OnToggleStreetlights = new UnityEvent();
void OnEnable()
{
OnToggleStreeLights.AddListener(ToggleLight);
}
void OnDisable()
{
OnToggleStreeLights.RemoveListener(ToggleLight);
}
void ToggleLight()
{
lightInChild.SetActive(!lightInChild.activeSelf);
}
}
Since I assume you're trying to swap the object's active state we can't just simply use OnEnable and OnDisable on the object itself as usual. Thus this script will go on a parent/container object with the Streetlight as a child. then pull the reference of the child object into the lightInChild field so that the script has direct access to it.
then in any script anywhere you can simply call
StreetLightScript.OnToggleStreetlights.Invoke();
and all lights currently in the scene will toggle their active state. And you never need to use the Find functions.
Also you can expand to having other, more specific events not just toggle. Such as OnIssueAllLightsOn.invoke() and OnIssueAllLightsOff.invoke()
Answer by QuintonH · Jan 27, 2016 at 03:04 PM
Here's a simple script that will get all the lights in your scene with the tag "StreetLights" and a function that allows you to turn them all off.
public GameObject[] streetlights;
void Start ()
{
streetlights = GameObject.FindGameObjectsWithTag("StreetLights");
}
void TurnOffAllLights()
{
foreach(GameObject light in streetlights)
{
light.GetComponent<Light>().enabled = false;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Can I choose what to pass into .getcomponent<{VARIABLE}>(); 1 Answer