Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity load and add animation controller dynamically

My code now:

Animator ContainerAnimator = this.GetComponent<Animator>();
ContainerAnimator.runtimeAnimatorController = Resources.Load("Assets/Cube") as RuntimeAnimatorController;
ContainerAnimator.Play("ContainerMoveUp");

I've got some dynamically created objects which have animators. these animators still don't have a controller in there which I'm trying to add, and it doesn't appear to work. any tips or tricks to do this? google is running out of answers

like image 525
Sten Martens Avatar asked Sep 03 '25 10:09

Sten Martens


2 Answers

Resources.Load("Assets/Cube") is likely returning null.

  1. You have to put the animation controller in a folder called "Resources" in the Assets folder. You must spell that correctly. Move your animation Contoller into this "Resources" folder.

  2. After this, remove the "Assets/" from the Resources.Load function. The path to pass to that should be a relative path in the Resources folder.

If the animation controller name is "Cube", you can then load it like this:

Resources.Load("Cube")

instead of:

Resources.Load("Assets/Cube")
like image 95
Programmer Avatar answered Sep 05 '25 01:09

Programmer


You might be loading the asset from the wrong directory or misplaced the filename. Here, you just remove the Assets/ prefix from the code to resolve the issue.

You can try the following implementation as well.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayAnimationDemo : MonoBehaviour
{
    [SerializeField]  
    Animator anim; // refer the animator via inspector

    void Start() {
        PlayAnimation(anim, "Cube", "ContainerMoveUp");
    }

    // animator is the animator object referred via inspector
    // fileName is the animator controller file name which should put under the Resources folder
    // animName is the animation clip name, you want to play
    void PlayAnimation(Animator animator, string fileName, string animName) {
        animator.runtimeAnimatorController = Resources.Load(fileName) as RuntimeAnimatorController;
        animator.Play(animName);
    }
}
like image 41
Codemaker Avatar answered Sep 04 '25 23:09

Codemaker