Search Unity

Baby question: Two codes running at once?

Discussion in 'Getting Started' started by Redicno, Jan 17, 2020.

  1. Redicno

    Redicno

    Joined:
    Jan 17, 2020
    Posts:
    2
    Is this the right place to ask questions about coding? I'm a few days in to trying to pick this up and have run in to a problem.

    I'm just spinning a cube and want it to spin in the opposite direction when I hit a key but it seems to be running both statements at the same time so instead of going the opposite direction is just slows down and the console will print both true and false .

    I'm sure its a vary simple solution but I know the answer to this will answer a lot of future questions!

    Thank you!

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.W))
    2.         {
    3.             spinRight = !spinRight;
    4.         }
    5.  
    6.         if (spinRight == true)
    7.         {
    8.             transform.eulerAngles += new Vector3(0, 180 * Time.deltaTime, 0);
    9.             print("true");
    10.         }
    11.         else
    12.         {
    13.             transform.eulerAngles += new Vector3(0, -180 * Time.deltaTime, 0);
    14.             print("false");
    15.         }
     
  2. Bill_Martini

    Bill_Martini

    Joined:
    Apr 19, 2016
    Posts:
    445
    it is impossible for spinRight to be true and false at the same time. spinRight is a boolean and is one or the other. Your code seems fine as shown but your spamming the console 60+ times a second. I think you might have two issues. One is in the code not shown and the other is your rotational speed.

    Instead of hard coding the value 180, make it a variable, call it speed. Before your Start() code define a public float speed with the value of 180f. Then change both lines 8 and 13 to speed and -speed. Save, select the gameobject the script is on and run, now you can adjust the speed in the inspector. Try slower.

    here is your code with my change, a little cleaner;
    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.W))
    2.         {
    3.             speed = -speed;
    4.         }
    5.         transform.eulerAngles += new Vector3(0, speed * Time.deltaTime, 0);
     
  3. Redicno

    Redicno

    Joined:
    Jan 17, 2020
    Posts:
    2
    Thank you so much! The damnedest thing happened where it started working as intended when I restarted unity and went back in. So i guess that's something I need to try next time.

    I'll punch in the code you suggest since it sounds a lot smarter.

    thank you