I’m using game events for pretty much the first time, and trying to set up an event when the player interacts with a door in the scene which will load the next scene. So far I have an events manager, door controller and door trigger. The code looks fine but doesn’t work in the scene and I get a null reference error for line 11 of the door controller.
I have a sprite with my level door image, 2D box collider and DoorController script, and parented to it an empty object for the trigger area with a 2D box collider and DoorTriggerPos script. I’ve made sure the door image box collider isn’t preventing the player from colliding with the trigger area., and I’ve matched the index id for the door and trigger in the inspector.
Pls help
Note: the OnDoorEnterPos and OnDoorEnterNeg methods in the event manager are structured differently because I’m playing around with different invocation syntax. It didn’t work before changing those.
public class EventManager : MonoBehaviour
{
public static EventManager current;
private void Awake()
{
current = this;
}
public event Action<int> OnDoorTriggerEnterPos;
public event Action<int> OnDoorTriggerEnterNeg;
public void DoorTriggerEnterPos(int id)
{
OnDoorTriggerEnterPos?.Invoke(id);
}
public void DoorTriggerEnterNeg(int id)
{
if(OnDoorTriggerEnterNeg !=null)
{
OnDoorTriggerEnterNeg(id);
}
}
}
public class DoorController : MonoBehaviour
{
public int id;
public void Start()
{
EventManager.current.OnDoorTriggerEnterPos += OnDoorOpenPos;
EventManager.current.OnDoorTriggerEnterNeg += OnDoorOpenNeg;
}
private void OnDoorOpenPos(int id)
{
if(id == this.id)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
private void OnDoorOpenNeg(int id)
{
if(id == this.id)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
}
}
}
public class DoorTriggerPos : MonoBehaviour
{
public int id;
private void OnTriggerEnter2D(Collider2D other)
{
EventManager.current.DoorTriggerEnterPos(id);
}
}