Search Unity

This code works but doesnt make sense to me?

Discussion in 'Scripting' started by axolotl123123, Jun 6, 2020.

  1. axolotl123123

    axolotl123123

    Joined:
    Jun 6, 2020
    Posts:
    2
    Code (CSharp):
    1. public class roator : MonoBehaviour
    2. {
    3.     float speed = 150.0f;
    4.     float speed1 = -150.0f;
    5.     // Use this for initialization
    6.     void Start()
    7.     {
    8.  
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update()
    13.     {
    14.         if (Input.GetKey("d")) transform.Rotate(Vector3.up * speed * Time.deltaTime);
    15.         if (Input.GetKey("a")) transform.Rotate(Vector3.up * speed1 * Time.deltaTime);
    16.     }
    17. }

    Im very new to coding and unity, and I found this code that does what I want it to but it doesn't make sense to me. For the if statement, after describing what has to happen (input.getkey), don't you have to put curly brackets around what you want it to do? Why is this working with no brackets or indentation?
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    indentation isn't required although it is preferred as it is easier to read. The brackets after an if statement are also not required. However, only the next line/statement will be affected by the if statement. { } are a code block in c# and with if statements are used to set a block of code to execute if the statement evaluates to true.
     
  3. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    All of what WarmedxMints said is correct.
    I'd like to add tho, that some people consider leaving out the brackets bad practice, since it doesnt really save you time, but can cause problems down the line if you have to add additional lines in the body of the if-statement. For example, re-adding brackets takes a lot more time than having them auto completed by the IDE directly from the beginning, and forgetting to re-add brackets can cause (sometimes hard to spot) bugs.
    I personally only leave out the brackets when i want to save the additional lines for readability reasons. This can happen, but very rarely, since often times when you have lots of small if-statements under each other, a switch-case would be a better solution.

    Anyways, for your main question, it does the same in this case, with or without brackets. I'd personally recommend adding them to not get into bad habits, but others may disagree.
     
    WarmedxMints and Kurt-Dekker like this.
  4. Modafuka

    Modafuka

    Joined:
    Nov 21, 2019
    Posts:
    45
    One line code?, better put them in the curly brackets for safe.