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);
}
}
}