I’m running into a problem with trying to access variables on a script attached to an instanced prefab. My code is such (Boo):
def Update ():
newZombie as GameObject = Instantiate(zombiePrefabObj, Vector3(0, 0, 0), Quaternion.identity)
...
enemies = GameObject.FindGameObjectsWithTag("zombie")
currentZombie = enemies[0].GetComponent("zombieScript") as zombieScript
...
for zombieObj in enemies:
zombie = zombieObj.GetComponent("zombieScript") as zombieScript
if Vector2.Distance(zombie.spriteRect.center, player.spriteRect.center) <
Vector2.Distance(currentZombie.spriteRect.center, player.spriteRect.center):
currentZombie = zombie
...
if currentZombie.health == 0:
Destroy(currentZombie)
player.score += 100
...
def OnGUI ():
enemies = GameObject.FindGameObjectsWithTag("zombie")
for obj as GameObject in enemies:
zombie = obj.GetComponent("zombieScript") as zombieScript
if zombie.visible == true:
zombie.Draw()
For some reason, when an enemy is destroyed, in (I think) the very same frame I run into a NullReferenceException (“Object reference not set to an instance of an object”) in the OnGUI function, specifically in the “if visible==true” line. I’ve confirmed via debug output that obj is not null, yet for some reason obj.GetComponent(“zombieScript”) returns null. What am I doing wrong here?
I’m wondering if maybe it’s a race, but Destroy() should be finished by the time OnGUI() runs as I understand it so I’m not sure why finding the GOs in OnGUI would return an object that was destroyed in Update.