0

I am following an Unity tutorial. I face a problem when trying to detect collision in the game. This is the error:

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

This is the script:

using UnityEngine;

public class Collide : MonoBehaviour
{
    public Movement movement;     // A reference to our PlayerMovement script

    // This function runs when we hit another object.
    // We get information about the collision and call it "collisionInfo".
    void OnCollisionEnter(Collision collisionInfo)
    {
        // We check if the object we collided with has a tag called "Obstacle".
        if (collisionInfo.collider.tag == "Obstacle")
        {
            movement.enabled = false;   // Disable the players movement.
            Debug.Log("Coollision occured");
        }
    }
}

derHugo
  • 49,310
  • 9
  • 37
  • 73
Atanas
  • 75
  • 1
  • 7
  • Which variable are you getting this null reference on? I can see 2 possible issues, but we don't know where the actual error is. – Eliasar Jan 28 '19 at 19:20
  • 3
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Eliasar Jan 28 '19 at 19:21
  • 1
    You have failed to assign a value to the serialized field `movement` in the inspector. As a result, it will always be null when you tried to access its members. – Serlite Jan 28 '19 at 19:34
  • Yes, thanks Serlite, I fixed the issue. – Atanas Jan 28 '19 at 19:51

2 Answers2

0

As i saw in the second image you have not added the movement reference to the movement field. At the same in the script also you are not assigning the reference. Try to assign at editor or you can create object.

0

The reason is you have not set the movement field in your Collide component. You can add it from the Unity Editor or add the following line in your Start function of Collide :

void Start()
{
    movement = GetComponent<Movement>();
}
Shahrokh
  • 33
  • 1
  • 6