I wanted to make a simple pause screen for my unity game, however, when i press the intended button (p) it doesn't display and it's not set as active.
Code excerpt:
using UnityEngine
public class pauseManager : MonoBehaviour
{
public GameObject pauseScreen;
void Start()
{
pause();
}
void Update()
{
if(Input.GetKeyDown(KeyCode.P))
{
pause();
}
}
public void pause()
{
pauseScreen.SetActive(true);
}
}
I set the gameobject that controls the pause screen as not active, so that when the game starts, it is not displayed, and i also used that game object in the pauseScreen variable.
CodePudding user response:
It looks like you are trying to check for keyboard input using the update function on a disabled object. This does not work because update does not run on game objects that are disabled. In order to work around this you will need to create an always active GameObject to control your pause screen.
Here is a possible fix:
- Create a separate game object that can run the update method at all times and attatch a new C# script there
- In the new C# script Create a reference in your script to the pause screen object GameObject you created
[SerializeField] private Gameobject pauseScreen;
- Now in your update method for this script we check if the 'P' key is pressed. If it is pressed we toggle the pause screen object's active state.
private void Update()
{
if(Input.GetKeyDown(Keycode.P))
pauseScreen.setActive(!pauseScreen.ActiveSelf);
}
}
Hopefully this should work for you.