C# variable type problem, always get NullRefExc

Hello. I'm playing around in Unity3D 3. I'm rewriting this JS code:

var prefabBullet:Transform;
var shootForce:float;
function Update () 
{
    if (Input.GetButtonDown("Fire1"))
    {
        var clone = Instantiate(prefabBullet, transform.position, transform.rotation);
        clone.rigidbody.AddForce(transform.forward * shootForce);
    }
}

Into C#:

using UnityEngine;
using System.Collections;

public class Shoot : MonoBehaviour {

    public Transform bullet;

    void Update() {
        if (Input.GetButtonDown("Fire1")) {

            Transform clone;

            clone = Instantiate(bullet, transform.position, Quaternion.identity) as Transform;
            clone.rigidbody.AddForce(transform.forward * 1000);
        }
    }
}

But I always get a "NullReferenceException: Object reference not set to an instance of an object" when I hit my Fire1 button. I think there is a variable type problem, but I cant solve it :( Please help. Thanks, Erhan

Your translation isn't entirely off, but your problem is not one of type and would have happened in the original javascript.

Here's a literal translation of the first script:

using UnityEngine;

public class Shoot : MonoBehaviour {
    public Transform bullet;
    public float shootForce;

    void Update() {
        if (Input.GetButtonDown("Fire1")) {
            Transform clone = Instantiate(bullet, transform.position, 
                                          transform.rotation) as Transform;
            clone.rigidbody.AddForce(transform.forward * shootForce);
        }
    }
}

For help with translation, this is a useful link.

Your problem is in one of these possible locations:

  • `Instantiate(bullet`... - is bullet set to something?
  • `clone.rigidbody`... - does bullet have a Rigidbody?

You can add some checks to avoid this problem altogether:

using UnityEngine;

public class Shoot : MonoBehaviour {
    public Transform bullet;
    public float shootForce = 1000.0f;

    void Update() {
        if (Input.GetButtonDown("Fire1") && bullet && bullet.rigidbody) {
            Transform clone = Instantiate(bullet, transform.position, 
                                          transform.rotation) as Transform;
            clone.rigidbody.AddForce(transform.forward * shootForce);
        }
    }
}