How do I assign an animation clip to a game object in cSharp ?
I have a class called myThirdPersonController with declarations of AnimationClip as follows :
public AnimationClip idleAnimation; // etc
and I want to add to idleAnimation my idle animation as done in the Editor by adding a clip, but through a script called StartUp accessing myThirdPersonController script. Here is my StartUp.cs script that I am using to access myThirdPersonController.cs :
public class StartUp : MonoBehaviour {
void Start() {
GameObject example = (GameObject)(Resources.LoadAssetAtPath("Assets/Models/character.FBX", typeof(GameObject)));
example.AddComponent("myThirdPersonController");
myThirdPersonController myCharacterController001 = example.GetComponent<myThirdPersonController>();
// set up animation clips here : clips are idle,walk,jump,run
CharacterController myCharacterController002 = example.GetComponent<CharacterController>();
myCharacterController002.center = new Vector3(0,1,0);
Instantiate(example, new Vector3(0,0,0), Quaternion.identity);
}
If I understand your question, it should be pretty easy:
// Where idleClip is an AnimationClip.
Animation anim = example.AddComponent<Animation>();
anim.AddClip(idleClip, idleClip.name);
[Updates based on comments]
I don't know of a way to query and extract animation clips directly from an FBX import. But, if creating a game object directly from an FBX behaves like a normal FBX import, then the game object will contain an animation component.
You can add this code snippet to test to see if an animation component is present on the game object.
Animation anim = example.animation;
if (anim == null)
{
Debug.LogError("Sorry, no animation component. This process won't work.");
return;
}
If an animation component was created by the FBX import process, then you can use the following process to extract the clips.
Animation anim = example.animation;
AnimationState state = anim["idle"];
if (state == null)
Debug.LogError("Missing idle animation.");
else
{
myCharacterController001.idleAnimation = state.clip;
}
state = anim["run"];
// Continue with the rest of the animations.
// ...
A final note: You can use this code snippet to examine the clips in an Animation component.
Animation anim = example.animation;
foreach (AnimationState state in anim)
{
if (state != null)
Debug.Log("Found clip: " + state.clip.name);
}