- Home /
NullReferenceException - Array of Transforms?
hello to all, sorry for my english, it is terrible, i know. I'm a very newbie with unity, and i'm making an android game. My problem is on my shooting script, i've isn't even finished him yet and i'm already getting errors D=
Here is my code:
using UnityEngine;
using System.Collections;
public class ShooterBehaviour : MonoBehaviour {
public Transform Bullet;
public int bulletNumber;
public float fireRate;
public float currentRate;
Transform[] bulletList;
void Start () {
Transform[] bulletList = new Transform [bulletNumber];
for (int i = 0; i < bulletNumber; i++){
bulletList[i] = Instantiate (Bullet, transform.position, transform.rotation) as Transform;
}
}
void Update () {
if(Input.GetKeyDown("space")){
Debug.Log("was pressed!");
Debug.Log("its time to fire!");
bulletList[1].gameObject.SetActive(true);
}
}
}
When i press the space bar, i was supposed to fire the first bullet from my array, but instead, i get one nullReferenceException. Does anyone can help me?
Please paste the error message from the console and/or show us what line is generating the error. You did initialize 'Bullet' by drag and drop in the Inspector?
Thanks for helping guys. Yes, bulletNumber is 20 in my inspector, and when i press play, i can see the 20 bullets instantiating. The error i get is:
NullReferenceException: Object reference not set to an instance of an object ShooterBehaviour.Update () (at Assets/Scripts/ShooterBehaviour.cs:25)
In general, when you get an exception or other error yo unwed to show people the whole error exactly as printed by the system so they can help you. When its an exception you need to give the entire stack trace.
Answer by robertbu · Apr 29, 2014 at 03:19 AM
Your bug is on this line 14:
Transform[] bulletList = new Transform [bulletNumber];
You declare 'bulletList' on line 8. Because you use 'Transform[]' at the start of line 14, you declare a local variable of the same name. This local variable hides the variable at the top of the file, so you never initialize the 'bulletList' that is used on line 24. The fix is to remove 'Transform[]' from the start of Line 14:
bulletList = new Transform [bulletNumber];
Dude, what a newbie mistake :T Btw, That is correct, thank you!
Your answer
Follow this Question
Related Questions
Attempt at creating an array of text files results in different errors 1 Answer
Object is null when it shouldn't be. 1 Answer
Why Again Arrays In ExecuteInEditMode() Gives NullReferenceException Errors?? 1 Answer
NullReferenceException happens only sometimes without cause? 2 Answers
Null Ref Exception on a script that should have a reference in it? 2 Answers