Animate instantiated object via C#
OK, new to this so patience please. So I'm creating a game where multiple enemies will be randomly generated, maybe even 100 per level or more (so searching for them by name is not that desirable a solution). The enemies are spawned based on a timer with a random number to offset it so it is not a steady stream. My problem is I want each of these enemies to be animated via C# script and I just can't seem to get it to work.
Basically I have one script which spawns the enemy with an instantiate command at a randomized location. I then want a separate script on the instantiated prefab object itself that tells it how to behave and move around. I can't seem to get the location of the object to move it around through. I've tried doing a GetComponent.Find to grab the object but its just not finding it. Any ideas on how I can get the transform location of a instantiated object and then manipulate it? Am I going about this all wrong? Here is a sample of roughly what I'm trying to do on the prefab script.
void update()
{
GameObject EnemySpawn = GameObject.Find("SpawnedEnemy(Clone)");
Vector3 EnemyPos = EnemySpawn.transform.position;
if (EnemyPos.y > 15f)
{
EnemyPos.y = EnemyPos.y - 1f;
EnemySpan.transform.position = EnemyPos;
}
}
For some reason, EnemyPos stays Null.
Jon
Answer by MajorBurn · Mar 31, 2017 at 03:40 PM
Figured it out. For posterity, here is the code.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MurderCube : MonoBehaviour {
Rigidbody EnemySpawn;
public Vector3 EnemyPos;
void Start()
{
EnemySpawn = transform.GetComponent<Rigidbody>();
}
void Update()
{
EnemyPos = EnemySpawn.transform.position;
if (EnemyPos.y > 10)
{
EnemyPos.y = EnemyPos.y - 0.2f;
EnemySpawn.transform.position = EnemyPos;
}
EnemySpawn.transform.Rotate(Vector3.up * Time.deltaTime*50);
}
}
Answer by MajorBurn · Mar 31, 2017 at 03:40 PM
Figured it out. For posterity, here is the code.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MurderCube : MonoBehaviour {
Rigidbody EnemySpawn;
public Vector3 EnemyPos;
void Start()
{
EnemySpawn = transform.GetComponent<Rigidbody>();
}
void Update()
{
EnemyPos = EnemySpawn.transform.position;
if (EnemyPos.y > 10)
{
EnemyPos.y = EnemyPos.y - 0.2f;
EnemySpawn.transform.position = EnemyPos;
}
EnemySpawn.transform.Rotate(Vector3.up * Time.deltaTime*50);
}
}
Your answer
