- Home /
Using ForEach Loop to change variables on prefabs
Hi all,
I have a bunch of instances of a prefab with a public boolean. I want to be able to change the boolean of all the instances on a click. Using a ForEach loop seemed the easiest way. I followed the code from the API site, but every time I try and play I get a "NullReferenceException: Object reference not set to an instance of an object" error. The code is below:
private GameObject[] units;
void Update () {
// Left click to select unit
if (Input.GetKeyDown(KeyCode.Mouse0))
{
units = GameObject.FindGameObjectsWithTag("unit1");
foreach (GameObject Hunter in units)
{
gameObject.GetComponent<unit1control>().active = false;
}
The offending line is gameObject.GetComponent().active = false; - anyone have an idea of how to resolve this?
Thanks!
Comment
Answer by Namey5 · May 09, 2017 at 07:22 AM
Change that line to;
Hunter.GetComponent<unit1control>().active = false;
As it stands, you are simply accessing a script attached to this GameObject as many times as there are Hunter objects, rather than accessing the component on those objects.