Search code examples
c#unity-game-engineunityscript

Don't know how to use SetActive() properly


So, my script that I've written isn't working fully. I have A pause button and when I press it, it triggers my bool and shows that its working properly but when I'm "Paused" my UI doesn't pop up and my game doesn't stop in the back ground. I hope you can understand clearly. I am a beginner!

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PauseManager : MonoBehaviour {

    public GameObject pauseMenu;

    public bool paused = false;

    public void start()
    {
        pauseMenu.SetActive(false);
    }

    public void update()
    {
        if(Input.GetButtonDown("escape"))
        {
            paused = !paused;
        }
        if (paused)
        {
            pauseMenu.SetActive(true);
            Time.timeScale = 0;

        }
        if (!paused)
        {
            pauseMenu.SetActive(false);
            Time.timeScale = 1;
        }

    }
    public void Resume()
    {
        paused = false;
    }
    public void pauseButton()
    {
        paused = true;
    }
}

Solution

  • Advice you change your code to this:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class PauseManager : MonoBehaviour {
    
        public GameObject pauseMenu;
    
        bool paused = false;
    
        void Start()
        {
            pauseMenu.SetActive(false);
        }
    
        void Update()
        {
            if(Input.GetButtonDown("escape"))
            {
                paused = !paused;
            }
            if (paused)
            {
                PauseGame();
    
            }
            if (!paused)
            {
                ResumeGame();
            }
    
        }
        void PauseGame(){
            pauseMenu.SetActive(true);
            Time.timeScale = 0f;
    
        }
    
        void ResumeGame(){
            pauseMenu.SetActive(false);
            Time.timeScale = 1f;
    
        }
        public void Resume()
        {
            ResumeGame();
        }
        public void pauseButton()
        {
            PauseGame();
        }
    
    
    }
    

    I think the problem is on that when you pause button pressed, timescale be 0, and update does not work.