- Home /
How can I use 1 key instead of two for toggling animation ?
Hi,
I have made animations for a flash light that can be holstered and un-holstered, using keys "f" and "g". It works fine, but I want to make the toggling on one key, "f". So when the player presses "f", it sets the bools in the "code" to their opposite. E.g if IsOn is false, it gets set to true upon the key being pressed.
The problem is, the bools are parameters in the mechanim animator and simply going like this "Bool = !Bool;" will not work because I get an error saying "Cannot convert boolean to unityengine.animator".
I am really stuck here and any help will be appreciated!
function Update () {
var IsOn : Animator = GetComponent(Animator);
var IsOff : Animator = GetComponent(Animator);
if(Input.GetKeyDown("f")){
IsOff.SetBool("IsOff",true);
IsOn.SetBool("IsOn",false);
}
if(Input.GetKeyDown("g")){
IsOff.SetBool("IsOff",false);
IsOn.SetBool("IsOn",true);
}
Answer by tanoshimi · Dec 01, 2013 at 08:50 PM
You've got several issues here:
Firstly, don't use GetComponent in an Update() loop. Get a reference to the Animator once in Start() and then reuse it.
In fact, you're getting two references to the same animator component - IsOn and IsOff both point to the same thing - this is definitely unnecessary.
By its very nature, a Boolean variable can only have two states. Therefore you don't need two Boolean variables to record both IsOn and IsOff - if IsOn is true then IsOff must be false (and vice-versa), so you only need a single variable, IsOn.
You can use GetBool to get the current status of the variable.
Try this instead:
#pragma strict
var anim : Animator;
function Start () {
anim = GetComponent(Animator);
}
function Update () {
if(Input.GetKeyDown("f")){
var isOn = anim.GetBool("IsOn");
anim.SetBool("IsOn",!isOn);
}
}
Thank you so much ! Worked Perfectly ! There needs to be more tutorials with animation regarding scripting !
Answer by markmmiller · Dec 01, 2013 at 08:53 PM
Hey there, I haven't used much of the mecanim stuff but the following code compiles and might solve your problem.
var IsOn : Animator = GetComponent(Animator);
var IsOff : Animator = GetComponent(Animator);
if(Input.GetKeyDown("f"))
{
IsOff.SetBool("IsOff", !(IsOff.GetBool()));
IsOn.SetBool("IsOn",!(IsOn.GetBool()));
}