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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Play animation on key press proble

Discussion in 'Scripting' started by Deanford, Jan 10, 2018.

  1. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Hi,

    I have an animation that changes my in game currency text to green but for some reason I cant get it to work? Probably an easy fix that I cant see, so help would be appreciated greatly!

    Code (CSharp):
    1.     public Text currencyText;
    2.     public int currency;
    3.  
    4.     //Animations
    5.     public Animation addCurrencyAnim;
    6.  
    7.     void Awake()
    8.     {
    9.         currency = 500;
    10.         addCurrencyAnim.enabled = false;
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.         currencyText.text = currency.ToString();
    16.  
    17.         if (Input.GetKeyDown(KeyCode.UpArrow))
    18.         {
    19.             currency += 50;
    20.             addCurrencyAnim.enabled = true;
    21.         }
    22.     }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    I think you have to use Anim.Play();
    Haven't tried just using an animation like that, though.
    You would also need to drag the animation onto the variable in the editor, of course.
     
  3. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Seems to be working like that but if I spam the key then it doesnt play everytime I press that key only when it has stopped playing and then plays again
     
  4. whileBreak

    whileBreak

    Joined:
    Aug 28, 2014
    Posts:
    289
    Every time you press the key stop the animation and start it over again.
     
  5. Deanford

    Deanford

    Joined:
    Oct 17, 2014
    Posts:
    93
    Does the same thing unfortunately! :(
     
  6. cybi_ic

    cybi_ic

    Joined:
    Jan 10, 2018
    Posts:
    1
    Under the Animator what are you using for a parameter? If it is a trigger you could reference your Animator and replace your:

    Code (csharp):
    1. addCurrencyAnim.enabled = true;
    with something like this:
    Code (csharp):
    1. <Animator>.SetTrigger("<string_param_name>");
    if it's a bool use SetBool; take a look at this SetBool example:

    https://docs.unity3d.com/ScriptReference/Animator.SetBool.html

    Unless you want it to loop (a lot) when you have the key down you might want to change your logic there and disable the Loop for the Animation in your Projects folder.