I have created an event that will run when an interactable object enters the radius of the player, but when attempting to subscribe other scripts to the events I get this error: NullReferenceException: Object reference not set to an instance of an object.
I thought at first it was a was a script execution order error and the other scripts were calling on the singleton instance before it was set, but when I changed the order to be sure the instance was first establish the error persisted. I found a thread with a similar problem here: Why can I not subscribe to an event of a singleton?
but they gave up on trying to find a solution.
This is my event handler script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
//System is require to used GameEvents
public class GameEvents : MonoBehaviour
{
/*
This is the Custom Event System.
This Script will contain ways to notify other scripts when an event occours.
Events like playerdeath, when a player can interact, or the end of a round.
All objects that react to events will need access to this script.
There can only be one instance of this object
This helps reduce the amount of dependancies
-S
*/
//This is the refference to the script.
public static GameEvents current;
private void awake()
{
current = this;
}
//This is the Event to allow the player to Interact
public event Action onInteractionRadiusEnter;
//This is the Fuction of that Event that notifies the other scripts the radius has been entered
public void interactionRadiusEnter()
{
if(onInteractionRadiusEnter != null)
{
onInteractionRadiusEnter();
Debug.Log("interaction radius entered");
}
}
public event Action onInteractionRadiusExit;
public void interactionRadiusExit()
{
if(onInteractionRadiusExit != null)
{
onInteractionRadiusExit();
}
}
}
and this is the script I am trying to subscribe to the event:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteraction : MonoBehaviour
{
private bool playerCanInteractWithObjects = false;
private GameObject objectToInteractWith;
private Interactable objectInteraction;
private void Start()
{
GameEvents.current.onInteractionRadiusEnter += playerCanInteract;
GameEvents.current.onInteractionRadiusExit += playerCannotInteract;
}
//This Triggers the enter event;
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Interactable"))
{
objectToInteractWith = other.gameObject;
GameEvents.current.interactionRadiusEnter();
Debug.Log("inteaction raduis entered");
}
}
//This triggers the exit Event
public void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.CompareTag("Interactable"))
{
objectToInteractWith = null;
GameEvents.current.interactionRadiusExit();
}
}
its worth noting that this error isn’t isolated to this script. I’ve create other scripts just to see if they can subscribe and they cannot. I am completely out of ideas on this one.