0
votes

I am trying to change character animations using a script, based on key inputs, but Unity seems to only play the default "standing idle" animation and occasionally switching to the "crouched idle", is there a different way to handle animations or am I just doing the script wrong? Here is my script as it currently stands

using UnityEngine;
using System.Collections;

public class CharacterControl : MonoBehaviour {

    private Animator animator;
    public bool crouched;
    private string sc;

    // Use this for initialization
    void Start () {

        animator = GetComponent<Animator> ();

    }

    // Update is called once per frame
    void Update () {

        if (crouched == true) {
            sc = "crouch";
        } else {
            sc = "standing";
        }

        animator.Play (sc + "_idle");

        if (Input.GetButton ("Fire3")) {
            if (crouched == false) {
                crouched = true;
            } else {
                crouched = false;
            }
        }

    }
}
4

4 Answers

0
votes

Try replacing

if (Input.GetButton ("Fire3")) {
    if (crouched == false) {
        crouched = true;
    } else {
        crouched = false; 
    }
}

with

if (Input.GetButton ("Fire3")) {
    crouched = true;
} else {
    crouched = false;
}

Now, when you hold down the "Fire3" button, your character should crouch, and when you release it he/she should stand again

Also a suggestion: Put the other code in the function (if (crouched == true) ... animator.Play (sc + "idle"); after this code (the Input.GetButton check). That way, your character should instantly start crouching the same frame that the button is pressed; otherwise, he/she will the frame after


Explanation

Input.GetButton will return true while you're pressing down (in the middle of clicking or touching) on the button each frame. Each time Update is called (around 1/60th of a second) your code will check if you're pressing down, and toggle crouched. When you click/tap the button, you'll likely be pressing down for a few frames, so crouched will switch from true to false, back and forth, a few times. In some cases (when you press down for an odd number of frames) crouched will be switched, but in other cases (when you press down for an even number of frames) crouched will stay as it was before you clicked on the button, preventing your character from crouching, or standing if he was crouching before.

Source: From the official API: Input.GetButton

0
votes

I would strongly suggest using animation states and transit from one to another when you get an input. Checkout my answer at: Unity 2D animation running partially

0
votes

Yes you can do the toggle action like this

void Update()
{
   if(Input.MouseButtonDown(2))
  {
    crouched = true;
  }
  if(Input.MouseButtonUp(2))
  {
    crouched  = false;
  }
}
0
votes

You can try this code:

crouched = Input.GetButtonDown("Fire3") ? true : false;