Home > Software design >  Add animator to instantiated prefab?
Add animator to instantiated prefab?

Time:01-09

I'm new to unity so bear with me... Created a model in Blender, complete with a metarig and animations.

Made a simple animator with an idle animation:

Animator

We have a spawner for the player (DinoSpawnLocation) with a script (DinoSpawner) to spawn the player (DinoPlayer), and the animator is added as a component:

Inspector

Here is the DinoSpawner script which should instantiate a prefab, and add the animator as a component:

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

public class DinoSpawner : MonoBehaviour
{

    public GameObject DinoSpawn;

    // Start is called before the first frame update
    void Start()
    {
        Spawn();
    }

    void Spawn()
    {
        Quaternion YPosition = Quaternion.Euler(0, -60, 0);
        transform.rotation = YPosition;
        GameObject clone = Instantiate(DinoSpawn, transform.position, transform.rotation);
        Animator animator = DinoSpawn.GetComponent<Animator>();
        animator.runtimeAnimatorController = Resources.Load("Assets/Animations/Dino Controller 1.controller") as RuntimeAnimatorController;
    }


}

And here lies the problem, a clone is produced, and the animator component is added, but it doesn't link the animator controller (highlighted in yellow):

enter image description here

I double checked the path in the Resource.Load() method, but for some reason it won't automatically add it, and I am not receiving any errors in the console.

I feel like it should be an easy fix but have been stuck on this problem for way too long, if anyone can help it would be much appreciated :)

CodePudding user response:

Well sounds like animator.runtimeAnimatorController = Resources.Load("Assets/Animations/Dino Controller 1.controller") as RuntimeAnimatorController; returns null.

Which makes sense because Resources.Load is supposed to be used on assets placed in a folder called Resources and then also would expect s path relative to this Resources folder .. so I pretty much doubt you have placed your asset in a folder like e.g.

Assets/Resources/Assets/Animations/...

Anyway in general Don't use Resources!

Simply assigning the controller asset correctly in your prefab and remove the lines after Instantiate.

  •  Tags:  
  • Related