- Home /
Null Reference Exception transform position y
Hi, Unity Answers Heroes! I am getting a Null Reference Exception, and although it might be simple to solve for most, any help would be great! Here is the code:
private GameObject leftAsteroid = null;
private GameObject middleAsteroid = null;
private GameObject rightAsteroid = null;
// Update is called once per frame
void Update () {
countdown -= Time.deltaTime;
if (countdown == -1.0f) {
leftAsteroid = Instantiate (Asteroid, Asteroid1);
middleAsteroid = Instantiate (Asteroid, Asteroid2);
rightAsteroid = Instantiate (Asteroid, Asteroid3);
}
//System.NullReferenceException error on the next line
if(leftAsteroid.transform.position.y <= -2.0f){
//code here
}
Answer by Cuttlas-U · Sep 09, 2017 at 07:29 PM
hi; change and try those lines like this :
leftAsteroid = Instantiate(Asteroid, Asteroid1) as GameObject;
Thank you very much for your help! With both tips from you and Positive7, it seems to be working!
Answer by Positive7 · Sep 09, 2017 at 07:24 PM
Because of the countdown leftasteroid is not spawned yet so it is null.
if (leftAsteroid != null && leftAsteroid.transform.position.y <= -2.0f) Debug.Log("OK!");
Your answer
Follow this Question
Related Questions
GameObject change Position after game started 1 Answer
Updating transform.position correctly to instantiated GameObjects 0 Answers
How do I instantiate on the game object's position that i put the script on 1 Answer
hello there I am Trying to Instantiate a 1 of 5 GameObjects 0 Answers
Instantiated script does not teleport 0 Answers