Frage

I have recently started playing working in unity3d and I run into the following problem following a tutorial.

The tutorial used unity-javascript but I prefer to use C#.

I was given the following code in Javascript

function Shoot() {
    var bullet = Instantiate(bulletPrefab, 
                             transform.Find("BulletSpawn").position,
                             transform.Find("BulletSpawn").rotation);
    bullet.rigidbody.AddForce(transform.forward * bulletSpeed);                      
}

and rewrote it in C#-code as

    void Shoot() {
    GameObject bullet;
    bullet = Instantiate(bulletPrefab, 
                         transform.Find("BulletSpawn").position,
                         transform.Find("BulletSpawn").rotation) as GameObject;
    bullet.rigidbody.AddForce(transform.forward * bulletSpeed); 
}

My problem is that the JS script works but with my C# code I get

NullReferenceException: Object reference not set to an instance of an object

on the line bullet.rigidbody.AddForce(transform.forward * bulletSpeed);

Any suggestions of what I might be doing wrong?

War es hilfreich?

Lösung

The return type of Instantiate is a Transform and cannot be casted directly to GameObject (as GameObject)

Your code should be:

void Shoot() {
    Transform bullet;
    bullet = Instantiate(bulletPrefab, 
                         transform.Find("BulletSpawn").position,
                         transform.Find("BulletSpawn").rotation);
    bullet.rigidbody.AddForce(transform.forward * bulletSpeed); 
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top