- Home /
NullReferenceException: Object reference not set to an instance of an object
hello guys !
i have a game object ( an ennemy) that is instansiated 1 second after the start of the game from a prefab.
with this code
#pragma strict
// this is the object(prefab) i am instantiating
public var zombprefab: Rigidbody;
var ennemies: GameObject[];
private var temps : float = 1f;
public var spawnV : float = 7f;
// this is the position on the scene to wich the zombie spawn
public var spawn: Transform;
function Start ()
{
}
function Update ()
{
// after 1 second of entering the game zombies are instantiated on the scene as long as they are less or equal to 10
// the instantiation rate define by the variable spawnV is of one zombie every 7 second
if(temps < Time.time && ennemies.Length < 10)
{
var zombieinstance: Rigidbody;
zombieinstance = Instantiate(zombprefab, spawn.position, spawn.rotation);
temps = Time.time + spawnV;
}
// i keep track of the number of ennemies on the scene by storing their number into the ennemies variable
ennemies = GameObject.FindGameObjectsWithTag("ennemie");
}
that zombie prefab that is istantiated , have a script that i am trying to access like fallow
#pragma strict
public var jumpspeed = 11f;
public var movespeed = 10f;
private var robcollider : CapsuleCollider;
var anim : tk2dSpriteAnimator;
var zombie : ZOMBIE;
function Start () {
anim = GetComponent(tk2dSpriteAnimator);
robcollider = GetComponent(CapsuleCollider);
// HERE I AM TRYING TO ACCESS THE SCRIPT THAT IS ATTACHED TO THE INSTANTIATED PREFAB
zombie = GameObject.Find("Zombie").GetComponent(ZOMBIE);
}
but i receive the fallowing error : NullReferenceException: Object reference not set to an instance of an object .
i understand it is because i am triying to access the script on the a gameobject that is not yet instantiated at the start of the game.
but my question is , how can i overcome this issue thanks in advance.
Answer by Azrapse · Oct 21, 2013 at 05:08 AM
If the zombie is spawned 1 second after the game starts, but you want your following script to start following 0 seconds after the game starts... well, I guess you see there is an inconsistency there. What is the follower script supposed to follow from second 0 to second 1?
If your zombie must spawn some time after game start, you have no other choice but make the follower script wait until there is a zombie to follow. Instead of having that last line in the Start()
method of the follower script, remove it and have this in Update()
.
function Update(){
if(!zombie){
var zombieObject = GameObject.Find("Zombie");
if(zombieObject){
zombie = zombieObject.GetComponent(ZOMBIE);
}
}
if(zombie){
// Do here the things that this follower script is supposed to do when it has found the zombie...
}
}