Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Finding the active state in an enum

Discussion in 'Scripting' started by Kickapk, Mar 13, 2021.

  1. Kickapk

    Kickapk

    Joined:
    Mar 7, 2021
    Posts:
    35
    I want my if statement to run only if a certain state is running in my enum. I am brand new to them.


    Code (CSharp):
    1.     public enum Movement { Right, Left, IdleRight, IdleLeft, JumpRight, JumpLeft }
    2.     public Movement MovementStates;
    3.  
    4.  
    5.             if(Input.GetKeyDown(KeyCode.Space) && Movement.IdleRight))
    6.             {
    7.                 MovementStates = Movement.JumpRight;
    8.             }
    This is basically what I am trying to do but I do not know the syntax or if it is event possible.

    I hope this explains what I am trying to do. I am totally new and just trying to learn as I go.
     
  2. Kickapk

    Kickapk

    Joined:
    Mar 7, 2021
    Posts:
    35
    Just to be clear, I copied the top of my code and put it in there just so you can see what I am trying to call. This is not how my script looks.
     
  3. Kickapk

    Kickapk

    Joined:
    Mar 7, 2021
    Posts:
    35
    I figured it out. Just in case someone can use this in the future here is what I did.

    Code (CSharp):
    1. if(Input.GetKeyDown(KeyCode.Space) && MovementStates == Movement.IdleRight)
     
  4. timfrombriz

    timfrombriz

    Joined:
    Jun 23, 2014
    Posts:
    30
    A few tips;

    public Movement MovementState

    Your storing a single state of one object, be clear in your definition so its clear when you read your code.


    If(Input.GetKeyDown(KeyCode.Space) && MovementState == Movement.IdleRight))

    use instead

    If(MovementState == Movement.IdleRight && Input.GetKeyDown(KeyCode.Space)))

    && logical AND requires both left and right conditions to be true. It always evaluates left first, and right only if left is true.

    Input.GetKeyDown is a method call to a class, and Movement.IdleRight is a simple boolean comparison. The later is far less expensive to execute on a CPU.

    Setting the order to least expensive to most expensive in && conditions means faster execution of code.