Im making the UI that appears when you press the pause button(escape key). My project has a GameManager empty object, a global canvas with an empty child and that child has its own child as a black image, and a sphere which will move and stop to show the effects of the pause. So my GameInput script is attached to the moving object which causes it to move and listens to escape key with legacy system which fires off “OnPause” event.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class GameInput : MonoBehaviour
{
public event EventHandler OnPause;
public static GameInput Instance { get; private set; }
[SerializeField]
private float speed;
private void Awake()
{
Instance = this;
}
private void Update()
{
PauseKeyListener();
transform.position += Vector3.up * speed * Time.deltaTime;
}
private void PauseKeyListener()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
OnPause?.Invoke(this, EventArgs.Empty);
}
}
}
This is listened by GameManager script which executes TogglePause function which fires off either OnGameUnpaused or OnGamePaused.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
public event EventHandler OnGamePaused;
public event EventHandler OnGameUnpaused;
private bool isGamePaused=true;
private void Awake()
{
Instance = this;
}
private void Start()
{
GameInput.Instance.OnPause += GameInput_OnPause;
}
private void GameInput_OnPause(object sender, EventArgs e)
{
TogglePause();
}
public void TogglePause()
{
isGamePaused = !isGamePaused;
if (isGamePaused)
{
Time.timeScale = 1f;
OnGameUnpaused?.Invoke(this, EventArgs.Empty);
}
else
{
Time.timeScale = 0f;
OnGamePaused?.Invoke(this, EventArgs.Empty);
}
}
}
This should then be heard by the GamePauseUI script which either hides or unhides the pause UI. But the Start function doesnt work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GamePauseUI : MonoBehaviour
{
private void Awake()
{
gameObject.SetActive(false);
}
private void Start()
{
//THIS DOESNT EXECUTE
GameManager.Instance.OnGameUnpaused += GameManager_OnGameUnpaused;
GameManager.Instance.OnGamePaused += GameManager_OnGamePaused;
}
private void GameManager_OnGamePaused(object sender, System.EventArgs e)
{
gameObject.SetActive(true);
}
private void GameManager_OnGameUnpaused(object sender, System.EventArgs e)
{
gameObject.SetActive(false);
}
}
I tested if OnGameUnpaused or OnGamePaused executes by doing a Debug.log in each branch of the TogglePause function(GameManager) and it does show which surely means the events are fired. But when I Debug.log in the Start function of the GamePauseUI script it doesnt work. Weirdly, the Awake call works, its just the Start function.