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

Animation will not play when I call it via script

Discussion in 'Scripting' started by PresidentPorpoise, Nov 25, 2016.

  1. PresidentPorpoise

    PresidentPorpoise

    Joined:
    Nov 6, 2016
    Posts:
    37
    I made a script that is supposed to play an animation when I press the "e" key.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DrawerInteract : MonoBehaviour
    6. {
    7.     public GameObject drawerOpen;
    8.     private Animation drawer;
    9.  
    10.     void Awake()
    11.     {
    12.         drawer = gameObject.GetComponent <Animation> ();
    13.     }
    14.    
    15.     void Open()
    16.     {
    17.  
    18.         if (Input.GetKeyDown ("e"))
    19.         {
    20.             drawer.Play();
    21.         }
    22.     }
    23.  
    The script appears to compile but the animation is not playing when I press the "e" key in-game. What is wrong with the code?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,181
    There's two ways to use GetKeyDown. There's the KeyCode version:

    Code (csharp):
    1. Input.GetKeyDown (KeyCode.E))
    which checks for the actual E key. Then there's the string version:

    Code (csharp):
    1. Input.GetKeyDown ("jump"))
    Which checks if the button with that name (here "jump") is pressed. Those names are defined in the Input Manager.

    You probably want to just use the keycode version!
     
  3. PresidentPorpoise

    PresidentPorpoise

    Joined:
    Nov 6, 2016
    Posts:
    37
    Thanks a lot, it worked!