I
I
Ivan Dogadov2020-06-25 18:08:27
Unity
Ivan Dogadov, 2020-06-25 18:08:27

Why does Unity3D get NullReferenceException: Object reference not set to an instance of an object?

private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.GetComponent<SpawnDestroyWall>().speed > 20 && other.tag == "Wall")
        {
            other.gameObject.GetComponent<SpawnDestroyWall>().Spawn();
        }
        if (other.gameObject.GetComponent<DestroyWallSpeed>().speed > 20 && other.tag == "WallParticl")
        {
            if (!other.gameObject.GetComponent<Rigidbody>())
            {
                other.gameObject.AddComponent<Rigidbody>();
                Destroy(other, 20);
            }
        }
    }

This code is tied to the ground (I don’t know if you need this information, but still). I have a similar code that is attached to a movable object and everything works, there are no errors.

Here's the code from the movable object, just in case:
private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Wall" && moveSpeed > 10)
        {
            other.gameObject.GetComponent<SpawnDestroyWall>().Spawn();
            Destroy(other, 20);
        }
        if (other.tag == "WallParticl" && moveSpeed > 10)
        {
            if (!other.gameObject.GetComponent<Rigidbody>())
            {
                other.gameObject.AddComponent<Rigidbody>();
                Destroy(other, 20);
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2020-06-25
@ivangrrrr

99% that some kind of GetComponent returned null, and you turn further. There is no check for what they encountered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question