# Getting an NRE when using delegates in Unity

I have a game where I have balls bouncing and you shoot them. Since I need a way to end the level when the player shoots all the balls I though I would create a game controller script which will register to an event from the ball script. In the awake function in the ball script I'm using this:

if (this.gameObject.tag == "SmallestBall") {
if(!touchedTheRope) {
countBalls(false);
}
}


NOTE: In this code here I'm not performing a check if(event != null) then execute - because I already know there is a problem. In the game controller script in the awake function I'm using this code:

UniversalBallScript.countBalls += CountBalls;


In the method CountBalls in game controller script I have Debug.Log to print out the number of balls. Because the small balls are being instantiated I first just performed a test where I check if the tag == "SmallestBall" and I just Debug.Log in the console, it gives me 28 small balls, but when I use the code above to call the event (if (this.gameObject.tag == "SmallestBall") etc... I get 24 balls and 4 null reference exceptions. I dont know if it has something to do with the fact that the small balls are being instantiated but I'm calling event registration in Awake and I also call that event in the Awake function, I have also tried to put this code:

if (this.gameObject.tag == "SmallestBall") {
if(!touchedTheRope) {
countBalls(false);
}
}


In OnEnable and OnDisable and its the same problem, I get 24 balls and 4 null reference exceptions. And BTW the null reference exceptions appear first and after that other 24 balls pass regularly. Does anyone have any idea?

• I have fixed the issue on how to track the balls, I just used a static variable. But if someone knows the answer on why this is happening I would love to hear it. Mar 20, 2015 at 19:11
• Since you don't have any answer yet, if the scope of the question changed, you should update the text of the question to specify only that, this way we'll have a better question with a better answer :) Mar 20, 2015 at 19:37
• The scope of the question did not change, the question is the same, why can my script register as a delegate for 24 objects and cant register for 4 objects, I just said I found another way to do it, but if there is a solution for this I can still use it. Mar 20, 2015 at 19:39
• I don't fully understand the question. Is there a chance you can ask it again in a different way? Mar 23, 2015 at 5:51

You have no control over the order in which scripts are Awake()ned.
In general, a script should only reference itself during Awake(). Any code which relies on other game objects already being initialized should be in the Start() event.