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

I made an animation script but have issues

Discussion in 'Scripting' started by Dragonxtamer, Sep 26, 2014.

  1. Dragonxtamer

    Dragonxtamer

    Joined:
    Nov 10, 2013
    Posts:
    23
    I made an animation script that opens and closes a drawer but when I press E it opens then closes.
    Code (csharp):
    1.  
    2. #pragma strict
    3.  
    4. var theDoor : Transform;
    5. private var drawGUI1 = false;
    6. private var doorIsClosed1 = true;
    7.  
    8. function Update ()
    9. {
    10.      var Checked : boolean = false;
    11.     if (drawGUI1 == true && Input.GetKeyDown(KeyCode.E) && !theDoor.animation.isPlaying)
    12.     {
    13.         if (doorIsClosed1)
    14.         {
    15.         theDoor.animation.CrossFade("Open1");
    16.         //theDoor.audio.PlayOneShot();
    17.         doorIsClosed1 = false;
    18.       Checked = true;
    19.         }
    20.     }  
    21.      if (!doorIsClosed1 && !Checked)
    22.         {
    23.         theDoor.animation.CrossFade("Close1");
    24.         //theDoor.audio.Play();
    25.         doorIsClosed1 = true;
    26.         }
    27. }
    28.  
    29. function OnTriggerEnter (theCollider : Collider)
    30. {
    31.     if (theCollider.tag == "Player")
    32.     {
    33.         drawGUI1 = true;
    34.     }
    35. }
    36.  
    37. function OnTriggerExit (theCollider : Collider)
    38. {
    39.     if (theCollider.tag == "Player")
    40.     {
    41.         drawGUI1 = false;
    42.     }
    43. }
    44.  
    45. function OnGUI ()
    46. {
    47.     if (drawGUI1 == true)
    48.     {
    49.         GUI.Box (Rect (Screen.width*0.5-51, 200, 160, 22), "Press E to open/close Drawer1");
    50.     }
    51. }
    52.  
     
  2. Dragonxtamer

    Dragonxtamer

    Joined:
    Nov 10, 2013
    Posts:
    23
  3. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    As soon as you hit the E key, the drawer opens. You try to set checked to true, but your update method always sets up the local boolean and initializes it with false again. The result: Both conditions for closing the drawer will be fullfilled in the next frame.
     
  4. Dragonxtamer

    Dragonxtamer

    Joined:
    Nov 10, 2013
    Posts:
    23
    How should I change it then?
     
  5. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    It depends. I think you want to be able to close the door with the E key again, so you can try moving the third if statement into the first which will also solve the issues i mentioned above because you won't run into the closing code without pressing the E key.