- Home /
How to Make Pressing a Button Not Trigger Other Events?
In my game I have a ball spawner that spawns a ball every time I tap the screen. I also have a pause button. When I tap the paused button, the spawner still spawns the ball even though I have told it not to using code. Here is my code:
Spawner: public GameObject Ball; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
Instantiate (Ball, transform.position, Quaternion.identity);
}
}
}
Pause Buttons: public class PauseControllerScript : MonoBehaviour {
public string mainMenu;
public bool isPaused;
public GameObject pauseMenuCanvas;
public GameObject spawner;
public GameObject cups;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (isPaused) {
pauseMenuCanvas.SetActive (true);
Time.timeScale = 0f;
spawner.GetComponent <BallSpawn> ().enabled = false;
} else {
pauseMenuCanvas.SetActive (false);
Time.timeScale = 1f;
}
}
public void Resume () {
isPaused = false;
}
public void Quit () {
SceneManager.LoadScene ("StartScreen");
}
public void Paused () {
isPaused = !isPaused;
}
public void Yes () {
isPaused = true;
}
}
Answer by vir1234 · Jul 21, 2017 at 04:13 AM
void Update ()
{
if (Input.GetMouseButtonDown (0) && !isPaused)
{
Instantiate (Ball, transform.position, Quaternion.identity);
}
}
and why r u using your pause code in Update() use On button click and if you want to avoid the click on pause bt dont use getmousebuttondown use ui image filled with screen size
you always instantiate
balls in the spawner class
and you didn't check anywhere in the spawner class whether game is paused or not, so before instantiating make sure your game is not paused as @vir1234 suggested. Other thing is that you have written code in the Update method which is not good technique. in your PauseControllerScript
make a UnityEvent
and invoke that event when you you paused your game ins$$anonymous$$d of checking in Update
.
public UnityEvent GamePausedEvent;
void Start () {
GamePausedEvent.AddListener(delegate {
if (isPaused) {
pause$$anonymous$$enuCanvas.SetActive (true);
Time.timeScale = 0f;
spawner.GetComponent <BallSpawn> ().enabled = false;
} else {
pause$$anonymous$$enuCanvas.SetActive (false);
Time.timeScale = 1f;
}
});
}
invoke this event where are are pausing your game. GamePausedEvent.Invoke();
I am an inexperienced programmer :-). I was watching a tutorial series and it told me to add the pause code in the update
Good learn other ways also to do same thing with other good techniques.I am not asking for adding code in the update method but code is executing in every frames and we don't want that extra work to processor so thats why i suggested. Writing code in update is not an issue just its for performances. I hope you will be experienced programmer in future :)