- Home /
Playing an AnimationClip
Hey all,
I'm having trouble playing an animation in code. The animation I want to play isn't playing.
This is what the Start looks like:
void Start()
{
gameObject.AddComponent("MeshFilter");
gameObject.AddComponent("MeshRenderer");
gameObject.AddComponent("Animation");
animation = (Animation)gameObject.GetComponent("Animation");
GameObject animationObject = Resources.Load("Models/character_wizard", typeof(GameObject)) as GameObject;
AnimationClip clip = animationObject.animation.GetClip("Run");
animation.AddClip(clip, "Run");
animation.animation.Play("Run");
mf = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter));
mr = (MeshRenderer)gameObject.GetComponent(typeof(MeshRenderer));
mf.mesh = (Mesh)Resources.Load("Models/character_wizard", typeof(Mesh));
mr.material.mainTexture = (Texture2D)Resources.Load("Textures/wizard", typeof(Texture2D));
gameObject.transform.localScale = new Vector3(100, 100, 100);
}
If I look in the inspector I can see that the clip has been added but it hasn't been set as a default or anything. I'm also not sure if this approach will work.
When I do animation.Play("Run"); Debug.Log(animation.isPlaying);
it outputs True.
Any advice will be much appreciated.
What happens ? Or is not happening and should ?
note : AddComponent returns the created component, you don't need to search them with GetComponent.
You should have :
mf = gameObject.AddComponent("$$anonymous$$eshFilter");
mr = gameObject.AddComponent("$$anonymous$$eshRenderer");
animation = gameObject.AddComponent("Animation");
It is cleaner and faster.
The animation doesn't play. Its just still standing mesh. If I drag the mesh into the scene from the assets it plays the animation. But when I create it in code it doesn't.
Do you have a reason to add components on runtime ins$$anonymous$$d of creating your prefab with all the components you need ?
try :
animation.Play();
ins$$anonymous$$d of :
animation.animation.Play("Run");
Doing it in code gives me a better idea of whats going on and also gives me more control over everything. I want to be able to create enemies during runtime which will also have animations.
If I do animation.Play("Run");
it still doesn't work. Do I need to link the armature or something like that in order to have it affect the mesh?
Are you sure the line :
AnimationClip clip = animationObject.animation.GetClip("Run");
returns something good ?
Your answer
![](https://koobas.hobune.stream/wayback/20220613110603im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Why i can't play animation clip i did ? Tried anything so far. 1 Answer
Sword is Messed Up 1 Answer
How can you code an animation? 1 Answer