Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Create Animation Controller Through Script?

Discussion in 'Scripting' started by Mashimaro7, Jan 15, 2021.

  1. Mashimaro7

    Mashimaro7

    Joined:
    Apr 10, 2020
    Posts:
    727
    Is there a way to create an animation controller through script? I have an animation that I want playing on many different objects, pretty much every object I make in my game.

    For convenience sakes, I wrote a script that adds an animation controller and plays a generic scale altering animation, kinda a popup animation whenever an object appears. I figured out how to add an animator, assign a new controller(through the inspector), and play the animation from that controller. It's only really a two step process, but is there a way to make it so I can just plop this script on any object I want animating and have it work without assigning an avatar from the inspector?

    Even if I can't "create" a new controller, maybe there's a way to assign the one that I've already created through script? I.E., access the animation controller through the resources folder or even have a "container" that just holds the controller and copy it over?

    Thanks in advance.

    Edit: Forgot to mention, I have tried putting an animator on an empty, with an animator and controller on it, assigning said controller to the current animator. But it always just returns null. Here's my script,

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PopupAnimate : MonoBehaviour
    6. {
    7.     Animator anim;
    8.     [SerializeField]
    9.     RuntimeAnimatorController controller;
    10.     void OnEnable()
    11.     {
    12.         if(controller = null)
    13.         {
    14.             controller = GameObject.Find("Animator Container").GetComponent<Animator>().runtimeAnimatorController;
    15.         }
    16.         anim = GetComponent<Animator>();
    17.         if(anim == null)
    18.         {
    19.             anim = gameObject.AddComponent<Animator>();
    20.         }
    21.         anim.runtimeAnimatorController = controller;
    22.  
    23.         anim.Play("Popup");
    24.  
    25.     }
    26.  
    27. }
    28.  
    Edit(again): sorry, for some reason checking if the controller was null was causing it to not be called? So I just have it not check if it's null, now it works just fine!
     
    Last edited: Jan 15, 2021
  2. FunDesign

    FunDesign

    Joined:
    Aug 20, 2017
    Posts:
    1
    You are missing a second equal sign in line 12 for the condition. It needs to be

    if(controller == null)

    rather than if(controller = null)
     
    Davex6 likes this.