- Home /
how to turn animator on if bool = true
hi i am having trouble trying to get my door open animator to work . i would like the animator component to be off on start and to come on when the bool chestOpened is true. i am coding in c# i just want a bit of code to say if bool == false animator not active if bool is true turn on animator (see picture for what i would like to control from script)
any help would be appreciated.
Answer by MIkeHewson86 · Oct 14, 2016 at 11:17 AM
I found out what my problem was. i wanted the door open animation in the animator to play when the bool chestOpened is true. I had not set up the animator properly. this tutorial helpped with that: https://www.youtube.com/watch?v=M1bEtHOE8z8
basically i created 2 animations in the animator the first one was doorClosed the second was door opening.
i created a bool in the animator called openDoor.
i set the doorClosed animation to default then created a transition from doorClosed to doorOpened. and in the inspector within the transition i added the condition that of openDoor is true then transition to doorOpen animation.
then i wrote a simple script as follows: using UnityEngine; using System.Collections; using UnityEngine.SceneManagement;
public class openDoor : MonoBehaviour {
public ChestKey chestKey;
public Animator anim;
public bool doorOpen;
// Use this for initialization
void Start ()
{
chestKey = GameObject.Find("Chest").GetComponent<ChestKey>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update ()
{
anim.SetBool("doorOpen", doorOpen);
if (chestKey.chestOpened)
{
doorOpen = true;
Debug.Log("door is open");
}
if (!chestKey.chestOpened)
{
doorOpen = false;
}
}
}
Answer by Zahiro · Oct 14, 2016 at 11:17 AM
Probably the easiest way you can do this is the way you enable and disable any other of the components , with GetComponent<>().enabled
So your script will look like this :
void Update () {
if (myBool) {
GetComponent<Animator> ().enabled = true;
}
}
Keep in mind that you should place this code on the same gameObject that the animator is
You can also disable the door collider (if you have one) by adding GetComponent<BoxCollider> ().enabled = false;
right after GetComponent<Animator> ().enabled = true;
Your answer
Follow this Question
Related Questions
Make a boolean positive and then negative with same button 1 Answer
Stop Animation State in Animator from Speeding Up after Playing it a Second Time? 0 Answers
How to check how many times an animation has played? 1 Answer
Add a bool to animator & activate by key press 1 Answer
how do i turn animator on from script if bool is true 2 Answers