hello i am reading the unity 3x game development i am following Prototyping and Scripting Basics bit of the the book.i made the game were u shoot by left clicking at the brick wall the game run but as soon as it does.I get a NullReferenceException: Object reference not set to an instance of an object Shooter.Update () (at Assets/Prefabs/Shooter.js:12) error here is my script
var bullet : Rigidbody;
var power : float = 1500;
var moveSpeed : float = 5;
function Update () {
var h : float = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
var v : float = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
transform.Translate(h, v, 0);
if(Input.GetButtonUp("Fire1"))
var instance: Rigidbody = Instantiate(bullet, transform.position,transform.rotation);
var fwd: Vector3 = transform.TransformDirection(Vector3.forward);
instance.AddForce(fwd * power);
}
The script seems fine. If you dragged your bullet rigidbody from the hierarchy, that could be your problem (might get destroyed or something before the script gets the reference).
Alright, checked your script again,. There are no curly brackets for your if statement, so only the next statement is conditional. If the bullet isn’t instantiated there won’t be an instance variable, but the script tries to access one regardless.
var bullet : Rigidbody;
var power : float = 1500;
var moveSpeed : float = 5;
function Update () {
var h : float = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
var v : float = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
transform.Translate(h, v, 0);
if(Input.GetButtonUp("Fire1"))
{
var instance: Rigidbody = Instantiate(bullet, transform.position,transform.rotation);
var fwd: Vector3 = transform.TransformDirection(Vector3.forward);
instance.AddForce(fwd * power);
}
}