- Home /
Can you animate instantiated prefabs?
I want to build an "army" of characters using an animated prefab. I get the "army" okay, but only the original prefab actually moves. Is there a secret to getting all of them to move at once?
// This is the army instantiation script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArmyController : MonoBehaviour
{
public GameObject MazeLowMan;
public Animator SpeedStateController;
public int numberArmy = 20;
private Vector3[] armyLoc;
private int xpos, zpos;
float time = 50, current;
void Start()
{
armyLoc = new Vector3[1 * numberArmy];
for (int i = 0; i < 1 * numberArmy; i += 1)
{
xpos = 480 + 2*i;
zpos = 480 + 2*i;
armyLoc[i] = new Vector3(xpos, 0.0f, zpos);
Vector3 location = new Vector3(xpos, 0.0f, zpos);
Instantiate(MazeLowMan, location, Quaternion.identity);
//print("army " + i + " (" + armyLoc[i].x + "," + armyyLoc[i].y + "," + armyLoc[i].z + ")");
}
}
// Spawn a new soldier every minute
private void FixedUpdate()
{
current += Time.deltaTime;
if (current + Time.deltaTime >= time)
{
int spawnLoc = Random.Range(0, numberArmy - 1);
Instantiate(MazeLowMan, armyLoc[spawnLoc], Quaternion.identity);
print("army " + spawnLoc + " (" + armyLoc[spawnLoc].x + "," + armyLoc[spawnLoc].y + "," + armyLoc[spawnLoc].z + ")");
current = 0;
}
}
}
// This is the animation "run" speed controller
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedSetter : MonoBehaviour
{
public Animator animator;
public float acceleration = 1f;
float m_TargetSpeed = 1f;
float m_CurrentSpeed = 1f;
static readonly int k_HashSpeed = Animator.StringToHash ("SpeedMultiplier");
void Update()
{
m_CurrentSpeed = Mathf.MoveTowards (m_CurrentSpeed, m_TargetSpeed, acceleration * Time.deltaTime);
animator.SetFloat (k_HashSpeed, m_CurrentSpeed);
}
}
// All 20 MazeLowMan GameObjects appear, but only the // MazeLowMan Prefab that is in the Hierarchy window runs forward.
I have a gif screen shot of the MazeLowMan prefab scripts being attached, but the website wouldn't upload it (too big probably).
Thanks in advance, Brent
Your answer
Follow this Question
Related Questions
Why is instantiated animator prefabs are not working properly? 2 Answers
How to animate an instantiated object in the timeline/director 2 Answers
how to call the animation of prefab 0 Answers
VUFORIA: Playing an animation for a instanced model? 2 Answers
How would i instantiate a prefab in the animation curve event? 1 Answer