Can someone tell me why this line of code is giving a NullReferenceException?

The title says it all really. Here is the piece of code.

if (collision.gameObject.tag == "Asteroid")
    {
        rigidbody.AddRelativeForce(horSpeedX + collision.gameObject.tag.Asteroid.horSpeedX * Time.deltaTime,horSpeedY + collision.gameObject.tag.Asteroid.horSpeedY * Time.deltaTime, 0);
    }

What I am trying to do with this is have an object inherit the colliding objects speed (which is collision.gameobject.tag.Asteroid).

Thanks in advance

1 Answer

1

Maybe your object has no rigidbody? Also there is no Asteroid member in a string (which a "tag" is). To access a component named Asteroid of a GameObject here you need to do this:

Asteroid a = collision.gameObject.GetComponent<Asteroid>();

in C# or this:

var a : Asteroid = collision.gameObject.GetComponent("Asteroid");

in javascript

If you have javascript that is calles Asteroid.js or a C# class Asteroid you can do what I wrote in the answer.