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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Looking for Open/Close Script on keypress for animation

Discussion in 'Scripting' started by MPL83, Apr 14, 2015.

  1. MPL83

    MPL83

    Joined:
    Sep 24, 2013
    Posts:
    9
    Hi there!

    Iam looking for a simple open/close on key input script. I try to unfold/fold a foldingtable and bed in a scene. I have both open and close animations, and tried several scripts but i always had trouble with having both animations triggered by 1 keypress (animations got mixed up). I got one script that exactly does what i want, even plays the animation backwards for closing but unfortunately on mouseclick.


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class anim : MonoBehaviour {
    5.  
    6.     public GameObject box;
    7.    
    8.     bool direction = false;
    9.  
    10.     private void OnMouseDown()
    11.     {
    12.         Debug.Log(direction);
    13.        
    14.         if (!direction)
    15.         {
    16.             box.GetComponent<Animation>()["Bew"].speed = 1;
    17.            
    18.            
    19.         }
    20.         else
    21.         {
    22.             box.GetComponent<Animation>()["Bew"].speed = -1;
    23.            
    24.             //if animation already finisihed, set time to end before playing it backwards
    25.             if(!box.GetComponent<Animation>().isPlaying){
    26.                 box.GetComponent<Animation>()["Bew"].time =box.GetComponent<Animation>()["Bew"].clip.length;
    27.                
    28.             }
    29.         }
    30.        
    31.         direction = !direction;
    32.        
    33.         box.GetComponent<Animation>().Play("Bew");
    34.     }
    35. }
     
  2. Xavior87

    Xavior87

    Joined:
    Feb 22, 2015
    Posts:
    23
    Well, its on a private. That could be a problem.
     
  3. Xavior87

    Xavior87

    Joined:
    Feb 22, 2015
    Posts:
    23
    Oh, here. Change private void OnMouseDown to void PlayAnimationNow. Then in the update function do this:

    void Update(){
    if(playing == false){
    PlayAnimationNow();
    playing = true;
    }
    }

    And at the end of the animation set playing to false. Try this!