- Home /
Global Variables & Object reference not set to an instance of an object
Hi... I need your help
I have a script "GameControl" and a script "SecurityCamera".
SecurityCamera checks if the player is seen by the camera and calls alarm. Alarm should be a game ending event and restart the level.
In GameControl I want to store variables and functions used by multiple things.
GameControl Script:
public class GameControl : MonoBehaviour {
public static GameControl control;
public void Respawn() {Code Stuff}
}
SecurityCamer Script:
void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player"))
return;
GameControl.control.Respawn();
}
Now I have the problem that this gives me the error:
NullReferenceException: Object reference not set to an instance of an object EnemyCamera.OnTriggerEnter (UnityEngine.Collider other) (at Assets/EnemyCamera.cs:47)
(double clicking it marks "GameControl.control.Respawn();" in my IDE)
---------------------------------------------------------------------------
I looked it up in my old files, where I once did the same and it worked.
Exactly the same script for "GameControl".
Only difference: how I call it
void Start () {
Save.onClick.AddListener(() => { GameControl.control.Save(); });
Load.onClick.AddListener(() => { GameControl.control.Load(); });
}
----------------------------------------------------------------------------
So why is this happening now? How can I fix it?
Answer by SkaredCreations · Dec 13, 2014 at 06:30 PM
If the player is spawned inside the security camera trigger when the level starts, then it's probably because GameControl.control hasn't been yet set (I suppose you're setting it in GameControl.Awake or GameControl.Start).
Player is spawned outside the trigger.
Edit: just found it in my old files... yeah, I forgot to properly set it in Awake >.<
Sry... I feel like I wasted your time now...
Answer by DRRosen3 · Dec 13, 2014 at 07:40 PM
You don't need the static variable (`public static GameControl control;`) INSIDE the GameControl script itself. Get rid of it.
In your SecurityCamera script you can add a reference to your GameControl script.
private GameControl gameControlScript = new GameControl():
Then you just call that reference in the code.
void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player"))
return;
gameControlScript.Respawn();
}
Your answer
