I may be missing something obvious, but can someone please explain to me just how animation layers work? The official tutorial and manual seemed to focus more on what they do rather than on how to use them. I’ve combed the answers and the forums and no one seems to be asking about this, so that tells me that I’m just missing it. So I’m going to ask:
How do I initiate an animation on a second layer?
I have a simple 2D game where the player stands still and can either jump or shoot. I want the shooting to be on a second layer, but the shooting animation is not being called.
UPDATE: I’ve discovered that the animations will play automatically. Which is nice, except that I only want to it to play when called. Scripting perhaps?
Scripting or state controls on the animation layer.
What do I need to do in order to script it? I’ve tried using Animation.Play, but I get a null reference exception (note: I’m not above admitting that I may just be using it wrong). I tried using SetTargetWeight, but it loops the clip in the background, so when I shoot, it starts mid-clip.
This is the code that I have for this. Above the “yield return new” command is where I want to start the animation.
void Fire ()
{
if (Time.time > nextFire) {
nextFire = Time.time + fireRate;
StartCoroutine (Shot ());
}
}
IEnumerator Shot()
{
yield return new WaitForSeconds (animationDelay);
Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
}
I can’t answer directly, notably because I’m just learning Unity Animation myself!
But first guess is using Animator.CrossFade with which you can set the state machine to any state on any layer.
I appreciate it, but I don’t think that’s going to do it. I’m trying to figure out a way to toggle the shoot animation on and off. I figure animation.enabled would work, but Unity freaks out when I try. So I don’t think I’m doing it right.
I actually feel sort of silly for this, but the answer lie in creating an empty animation state to be the default animation on the upper layer.
First you need to set the weight of the layer, either in the editor or by script at runtime when needed. By default the weight of a new layer is set to 0.
http://docs.unity3d.com/ScriptReference/Animator.SetLayerWeight.html
Exactly, create a first empty state in your upper layer and set it as your default state and then create your jump state.
Best regards,