How Do You Create a New GameObject with an Animation via C#?

I’m trying to create a new GameObject in C# and add a new animation to it. I get as far as AddComponent Animator() but then I’m not sure what to do. All the advice I can find is about doing this to an existing object in the Unity GUI. I have a sprite sheet but I don’t know how to create a animation controller and animation in C#. It also doesn’t look like you can create an animation in Unity without it being attached to a GameObject already.

To create a new GameObject with an animation via C#, you can follow these steps:

Create a new GameObject by using the GameObject.CreatePrimitive() method. This method creates a new GameObject with a default 3D primitive mesh (such as a cube, sphere, or capsule).

GameObject myGameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);

Add an Animator component to the GameObject by using the AddComponent() method. This will allow you to control the animation of the GameObject.

myGameObject.AddComponent<Animator>();

Create an AnimationClip that defines the animation for the GameObject. You can do this by using the AnimationUtility.CreateAnimationClip() method. This method creates a new AnimationClip and returns a reference to it.

AnimationClip myAnimationClip = AnimationUtility.CreateAnimationClip(
    "MyAnimation", // Name of the AnimationClip
    new List<EditorCurveBinding>() // List of animation curves
);

Add animation curves to the AnimationClip by using the AnimationUtility.SetEditorCurve() method. This method adds a new animation curve to the AnimationClip, which defines how a property of the GameObject will be animated over time.

AnimationUtility.SetEditorCurve(
    myAnimationClip, // AnimationClip to add the curve to
    new EditorCurveBinding() { // Animation curve binding
        type = typeof(Transform), // Type of the component to animate
        propertyName = "localPosition.x" // Property to animate
    },
    new AnimationCurve() // Animation curve
);

Assign the AnimationClip to the Animator component by using the runtimeAnimatorController property. This will make the Animator use the AnimationClip to animate the GameObject.

myGameObject.GetComponent<Animator>().runtimeAnimatorController =
    new UnityEditor.Animations.AnimatorController() {
        name = "MyController", // Name of the AnimatorController
        animations = new AnimationClip[] { myAnimationClip } // AnimationClips to use
    };

Start the animation by calling the Play() method of the Animator component. This will make the Animator start playing the animation from the beginning.

myGameObject.GetComponent<Animator>().Play("MyAnimation");

Note that the steps described above are specific to the Unity Editor and will not work in a built game. In a built game, you will need to use the Unity Animation API to create and control animations. You can find more information about this in the Unity documentation.