I'm using Unity. I have an empty elements called GameElements
which I programmatically add child elements to (players can spawn these objects themselves in-game).
Within my script Play.cs
I have a method to handle the onclick event when someone clicks the Play image/button. I want to run through all of the child elements of my GameElements
object and run the method on the script Circle.cs
which is attached to those child elements.
Here is my Play.cs
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Play : MonoBehaviour
{
public GameObject GameElements;
public Circle CircleScript;
public void OnMouseDown()
{
Debug.Log("Clicked!", gameObject);
GameElements = GameObject.Find("GameElements");
// Loop through game objects and init them
Transform[] allChildren = GameElements.GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren) {
// do whatever you want with child transform object here
Debug.Log("child...", child);
CircleScript = (Circle) child.GetComponent(typeof(Circle));
CircleScript.Init();
}
}
}
The click events do generate a Debug Log in console for the child objects as expected.
However I get the following:
NullReferenceException: Object reference not set to an instance of an object
Play.OnMouseDown () (at Assets/Game/Scripts/Play.cs:22)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
Any help appreciated.
GameElements
here:GameElements = GameObject.Find("GameElements");
? \$\endgroup\$ – Skalli Aug 27 '18 at 15:44var circles = GameElements.GetComponentsInChildren<Circle>();
instead of iterating in transforms to get the Circle component? In that way you know you iterate on valid objects. \$\endgroup\$ – arielsan Aug 28 '18 at 1:50