- Home /
Mecanim triggering an animation from object
I've been going crazy trying to figure out how to trigger an animation. My character uses mecanim, and I've been trying to make an animation trigger from inside of mecanim without a keypress. It feels like I've tried everything. I've tried putting an animation list on the character and trying to trigger it from the cube trigger, but it says "animation not found". I've tried to put the animation in the mecanim hierarchy, but still says animation not found. How can I trigger an animation is there some type of code I haven't tried.
I've tried the legacy way, and it will work if I'm not using mecanim, but as soon as I use mecanim it stops working.
I just need to be pushed in the right direction for this.
$$anonymous$$ake a new state in Animator add a Transition with a bool and Set it true in OnTriggerEnter() or OnCollisionEnter() or whatever.
Answer by TheOneFreeMan · Aug 06, 2015 at 12:42 AM
If you want to make unity play an animation when you collide with another object, you need only a simple script that uses OnCollisionEnter() and also accesses the animator controller. A rough example of some C# code would look like:
anim = GetComponent();
void OnCollisionEnter (Collider other) {
if (other.tag == "Object Name")
anim.SetBool ("Name of bool", false);
else
anim.SetBool ("Name of bool", true);
}
Finally understand it. I use an on collision enter with your code modified a bit to suit the rest. But thank you so much. Everyone here has helped out a million and I can finally move on to the next steps of the project.
Answer by Menatombo · Aug 06, 2015 at 10:59 PM
using UnityEngine;
using System.Collections;
public class Animate : MonoBehaviour {
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter (Collision collision) {
if (gameObject.tag == "t_Trigger_Pole")
anim.SetBool ("Fight_1", false);
else
anim.SetBool ("Fight_1", true);
}
}
This is my code to attempt to trigger the mecanim animation. I have a Fight_1 animation set in a pole that is an attack dummy. When you collide with the pole you should start the fight_1 animation. When I put this code in to the pole it says there is no animator attached to pole so it cannot access it.
My question is do I have to put this script on the player character? If so it's going to get messy, but at least it's a step in the right direction.