Please Help! Daunting error comes again and again

I keep getting this error million times… I want to fix it once and for all at least wanna know why and what it is exactly. I am new to Unity C#.

ERROR:
NullReferenceException: Object reference not set to an instance of an object
rayCastTEst.Update () (at Assets/iMadeScripts/rayCastTEst.cs:23)

So this is want i want to do. There is an empty game object in front of the camera a lil far. It has a script which creates a cube at its location. There’s a sphere kinda below the camera which I want to cast a ray towards that empty game object and when ever the cube is created I want to get it and pass it as an argument to function which compares 2 gameobjects.

Code attached to the Empty Gameobject:

using UnityEngine;
using System.Collections;

public class TestScript : MonoBehaviour {

    GameObject box;
    // Use this for initialization
    void Start () {
   
        box = GameObject.CreatePrimitive (PrimitiveType.Cube);
        box.transform.position = transform.position;
    }
   
    // Update is called once per frame
    void Update () {
   
    }

    public void Comparer (GameObject hittedObject)
    {
        if (box == hittedObject) {

            Debug.Log ("They are same!");
        }
    }
}

Code attached to the Sphere:

using UnityEngine;
using System.Collections;

public class rayCastTEst : MonoBehaviour {

    Ray ray;
    RaycastHit hit;
    TestScript tp;
    // Use this for initialization
    void Start () {

        tp = GetComponent <TestScript> ();
   
    }
   
    // Update is called once per frame
    void Update () {

        ray = new Ray (transform.position , transform.right);
        if (Physics.Raycast (ray, out hit)) {

            Debug.Log (hit.collider.gameObject.name);
            tp.Comparer (hit.collider.gameObject);
        }
   
    }
}

It could be that TestScript tp is not being found, try changing line 12 to

tp =GameObject.FindWithTag("CUBETAG").GetComponent<TestScript>();

and assign CUBETAG tag to the cube object.

NullReference errors occur because a gameobject/script can’t be found.

Nope! Same error this time twice. One for line 12 (that u told) and other one as usual for line 23

GetComponent() will gets a component attached to the current gameobject. Unless I’m misunderstanding what you wrote you have TestScript attached to an empty gameobject not the sphere. your sphere has no TestScript component so “tp” is never assigned. You need a reference to the empty gameobject that contains the component that you want.

This is essentially what @image28_1 was solving for you. When trying his solution did you actually give your empty gameobject a tag that matched what you passed into FindWithTag()?

1 Like

thank you I got it now! :slight_smile:

1 Like