Hello Guest

Author Topic: How to change sprite animation at run time with c#?  (Read 7158 times)

Euthyphro

  • Newbie
  • *
  • Posts: 20
    • View Profile
How to change sprite animation at run time with c#?
« on: September 10, 2013, 06:00:58 am »
I'm trying to figure out how to change the sprite animation library of a game object so I can change the current playing animation clip to one from a different library. Can someone please share how to do this in C#?

For example, one Library called "AnimationSetOne" with a dozen clips, and another library called "AnimationSetTwo" with another dozen. How can I change the current library of a game object so I can then use the .Play(anim); method to change a sprite animation clip? I want to be able to do this during run time in c#, could only find a javascript example that didnt work.



Thanks!

gary-unikronsoftware

  • 2D Toolkit
  • Jr. Member
  • *
  • Posts: 74
    • View Profile
Re: How to change sprite animation at run time with c#?
« Reply #1 on: September 10, 2013, 10:04:34 am »
Hi,

I've made a simple c# script that loads in another sprite animation resource and plays a clip when 'x' is pressed.  You should be able to convert it so it does what you want...

Code: [Select]
using UnityEngine;
using System.Collections;

public class ChangeAnimation : MonoBehaviour {

public tk2dSpriteAnimator myAnimator;

void Update ()
{
if(Input.GetKey("x"))
{
tk2dSpriteAnimation newAnimationLibrary = Resources.Load ("shipAnim", typeof(tk2dSpriteAnimation)) as tk2dSpriteAnimation;
myAnimator.Library = newAnimationLibrary;
tk2dSpriteAnimationClip myClip = myAnimator.GetClipByName("shipdestroy");
myAnimator.Play(myClip);
}
}
}

Remember, any resources you want to load in at run time need to go in a folder called 'Resources' in the assets folder.  Also, a sprite animator should exist in the Hierarchy window and be dragged to the 'myAnimator' slot on the script.

Hope this helps.