0

I have 2 code:

code 1:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowCube : MonoBehaviour
{
    public GameObject cube;
    public Vector3 cubePov;
    public Vector3 cubePovStart;
    public Vector3 camPov;
    public CollisionDetection script;

    void Start()
    {
        cube = GameObject.Find("Cube");
        script = cube.GetComponent<CollisionDetection>();
    }

    void Update()
    {
        cubePov = (GameObject.Find("Cube")).transform.position;
        camPov = transform.position;

        if (script.CollisionDown == true)
        {

        }
    }
}

code 2:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CollisionDetection : MonoBehaviour
{

    public bool CollisionUp;
    public bool CollisionDown;
    public string ObjectName;

    void Start()
    {
        ObjectName = this.gameObject.name;
    }

    void Update()
    {

    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.name == "Cube")
        {
            CollisionUp = true;
            CollisionDown = false;
        }
    }

    void OnTriggerExit2D(Collider2D col)
    {
        if (col.gameObject.name == "Cube")
        {
            CollisionUp = false;
            CollisionDown = true;
        }
    }


}

but I always get this error code - "NullReferenceException: Object reference not set to an instance of an object FollowCube.Update () (at Assets/FollowCube.cs:24)"

can someone please help me it? i think it means that when i typed script.CollisionDown that there isn't any variable named CollisionDown but there is.

  • *"i think it means that"* ...you're guessing. Don't guess. Step through the code in the debugger and find what it is that's `null`. – madreflection Sep 28 '20 at 15:57
  • It means that either `(GameObject.Find("Cube")` in `Update` or `cube.GetComponent()` in `Start` returns `null` ... – derHugo Sep 28 '20 at 16:52

0 Answers0