Question

So I'm currently working on my game project using unity3D and I came across this weird error.

I'm trying to instantiate and shoot a projectile forward. here's my Update code:

if (Input.GetButtonUp("Fire1")){
        Vector3 frontDir = transform.TransformDirection(Vector3.forward * arrowShotForce);

        if (chosenProj){
            Rigidbody shotProj = Instantiate(chosenProj, transform.position, transform.rotation) as Rigidbody;
            shotProj.AddForce(frontDir);
        }
    }

when I tried to play the script, it gets error at shotProj.AddForce(frontDir) saying NullReferenceException: Object reference not set to an instance of an object

I've checked the 'chosenProj' gameobject and have assigned it with a projectile model and I still got this error. the projectile won't fly forward and I feel so dumb because I've worked with unity for a month now

any idea why?

THX b4

Was it helpful?

Solution

Your code, where you get a NullReferenceException in the last line:

Rigidbody shotProj = Instantiate(
    chosenProj, transform.position, transform.rotation)
    as Rigidbody;
shotProj.AddForce(frontDir);

In the last line something must be null, or otherwise you wouldn't get the exception. Since frontDir is a Vector3 value type, the only reference type that can be null is shotProj.

How could it be null? Well, when the return value of Instantiate() cannot be cast to a Rigidbody, the as Rigidbody expression will return null.


So, I conclude that your chosenProj is not a RigidBody. It is actually a GameObject that has a rigid body component on it. To get the RigidBody, use this:

GameObject shotProj = (GameObject)Instantiate(chosenProj, transform.position, transform.rotation);
shotProj.rigidbody.AddForce(frontDir);

GameObject class documentation has more info on how to get components from game objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top