- Home /
NullReferenceException: Object reference not set to an instance of an object spawn.Update () (at Assets/spawn.cs:24)
I am fairly new to Unity and I am stuck. One of the problem I have is that if there are 2 different scripts, and both have a Start() and Update(), which scripts functions run first? hmmm.
And also im running in to this error, and I can't seem to figure it out: NullReferenceException: Object reference not set to an instance of an object spawn.Update () (at Assets/spawn.cs:24)
localVariables is a script for every clone objects created by//instantiate(object)
each object should have its own version of localVariables, meaning different index numbers
public class localVariables : MonoBehaviour {
public static int index;
void Start () { index = -1; }
public static int get(){
return index;
}
public static void set(int a){
index = a;
}
}
Then this script clone an object x amount of times and I want to save a number into the clone object's index variable:
public class spawnBase : MonoBehaviour {
public Transform baseSpawn;
// Update is called once per frame
void Update () {
GameObject temp= Instantiate(baseSpawn,new Vector2(spawnObject.position.x,0.73f),spawnObject.rotation)as GameObject;
int index = globalScript.getFreeQueue();
//ERROR below this line
temp.gameObject.GetComponent<localVariables>().index = index;//line24 RUNTIME ERROR
}}
Globalscript is just a script attached to an empty gameobject that holds globalVariables.
Can anyone point me in to the right direction please? Leave any comments and suggestions.
Answer by MohanadHamed · May 30, 2014 at 01:31 PM
You should not instantiate objects in Update() function, The update is called in each frame which means that you will create around 60 objects per second, this will lead to unexpected results.
You should move your code to a function called once like Start() or to other function called by you when needed.
That is not the problem though. That is part of the code striped down. I have flags of bools which is triggered but buttons. How do I fix that null problem thought ? :(
I found the actual error now, but I don't know why it is happening.
GameObject temp= Instantiate(baseSpawn,new Vector2(spawnObject.position.x,0.73f),spawnObject.rotation)as GameObject;
if(temp==null){
Debug.Log("its not supposed to be null");
}
the object shows on both the camera and as a clone on the Hierarchy window, but it's null... what?!