NullReferenceException on Invoke in another class
I am trying to use the Invoke() method to run the open and close door methods in one class. The TestRaycast class runs the method() in OpenCloseObjects, but it runs through the mothod and then gives me a NullReferenceException on the Invoke() method.
TestRaycast Method:
using UnityEngine;
using System.Collections;
public class TestRaycast : MonoBehaviour
{
public static RaycastHit hit;
OpenCloseObjects test = new OpenCloseObjects();
void Update ()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out hit))
{
//Debug.Log (hit.transform.tag);
if (Input.GetMouseButtonDown (0))
{
test.method();
}
}
}
}
OpenCloseObjects Method:
using UnityEngine;
using System.Collections;
public class OpenCloseObjects : MonoBehaviour
{
//public RaycastHit hit;
bool doorLocked;
private bool doorOpen;
public void method()
{
if(doorLocked == false)
{
//door1
if (TestRaycast.hit.transform.tag == "front door" && doorOpen == false)
{
Debug.Log("hi");
TestRaycast.hit.collider.gameObject.GetComponent<Animation>().Play("OpenDoor1");
Invoke("DoorOpen", 5);
}
if (TestRaycast.hit.transform.tag == "front door" && doorOpen == true)
{
Debug.Log("bye");
TestRaycast.hit.collider.gameObject.GetComponent<Animation>().Play("CloseDoor1");
Invoke("DoorClosed", 5);
}
}
}
public void DoorOpen()
{
doorOpen = true;
}
public void DoorClosed()
{
doorOpen = false;
}
}
Answer by petraszd · Jan 05, 2017 at 02:08 PM
This line is a problem: OpenCloseObjects test = new OpenCloseObjects();
You are not suppose to initialize MonoBehaviour object using simple constructor with new
. In fact, Unity is suppose to warn you about doing it. So, either:
Attach OpenCloseObjects
component to same object or to different object in the editor or dynamically.
Or if you really, really need to create new object, than you can do fallowing:
OpenCloseObjects test = null;
void Start()
{
GameObject testObject = new GameObject();
test = testObject.AddComponent<OpenCloseObjects>();
}
void Update()
{
// ...
}
Not sure why would you do that, though.
Your answer
Follow this Question
Related Questions
Time.deltatime not working. 1 Answer
Visual Studio 2015 keeps crashing... 1 Answer
Object reference not set to an instance of an object 0 Answers
Nav Mesh Problem with SetDestination 1 Answer