Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Why does both my input run instantly instead of line by line

Discussion in 'Scripting' started by driceyz, Sep 25, 2022.

  1. driceyz

    driceyz

    Joined:
    Jul 27, 2021
    Posts:
    6
    when i press space my first if function works but my second if function also executes but why.
    how do i make so that only the first if function work but the second doesnt

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Inputtest : MonoBehaviour
    {

    bool paused;
    // Update is called once per frame
    void Update()
    {
    if(Input.GetKeyDown(KeyCode.Space))
    {
    Debug.Log("clicked space");
    paused = true;
    Debug.Log(paused);
    }
    if(paused & Input.GetKeyDown(KeyCode.Space))
    {
    Debug.Log("cliked space");
    paused = false;
    }
    }
    }
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,647
    Because... when you get to the next if statement,
    pause
    is true, thus it will execute.

    You want to use
    else if
    , and you also want to check paused is false too.

    Code (CSharp):
    1. if(!paused && Input.GetKeyDown(KeyCode.Space))
    2. {
    3.     Debug.Log("Clicked Space");
    4.     paused = true;
    5.     Debug.Log(paused);
    6. }
    7. else if(paused && Input.GetKeyDown(KeyCode.Space))
    8. {
    9.     Debug.Log("Clicked Space");
    10.     paused = false;
    11. }
    Also you generally want to use
    &&
    rather than
    &
    99% of the time.

    Also use code tags next time, please.
     
  3. driceyz

    driceyz

    Joined:
    Jul 27, 2021
    Posts:
    6
    Thanks man it works