- Home /
How can I make a prefab object from a list to move?,How can I make an object from a list to move by itself?
So, I have a list of prefab objects and i randomly instantiate them at an fixed y axis position and i need them to move till -70. The problem is that I don't know which one will be spawned. Tried this:
Enemies[Random.Range(0, 8)].transform.Translate(Vector3.forward * Time.deltaTime * -5f, Space.Self);
but dosen't work... This is my script so far:
public class Enemy : MonoBehaviour
{
public float spawnRate = 1f;
private float nextTimeToSpawn = 0f;
public List<GameObject> Enemies;
// Update is called once per frame
void Update()
{
Enemies[Random.Range(0f, 8f)].transform.localScale = new Vector3(Random.Range(50f, 100f), Random.Range(50f, 100f), Random.Range(50f, 100f));
Vector3 position = new Vector3(Random.Range(-8f, 8f), -20f, Random.Range(-4f, 5f));
Enemies[Random.Range(0f, 8f)].transform.Translate(Vector3.forward * Time.deltaTime * -5f, Space.Self);
if (Time.time >= nextTimeToSpawn)
{
Instantiate(Enemies[Random.Range(0f, 8f)], position, Quaternion.identity);
nextTimeToSpawn = Time.time + 1f / spawnRate;
}
}
}
,So, I have a list of objects, they are instantiated randomly at a fixed y axis position, and i want them to move on y axis by them-self. I tried this: Enemies[Random.Range(0, 8)].transform.Translate(Vector3.forward * Time.deltaTime * -5, Space.Self);
Enemies is the list of prefab objects and because i don't really know which one is going to be instantiated I used Random.range but they are not moving.
Answer by Nivbot · Mar 06, 2019 at 01:55 PM
Put the movement script on the object you instantiate. Unless there is a good reason not to, all game objects should be controlled by scripts on themselves
Answer by xxmariofer · Mar 06, 2019 at 02:03 PM
Enemies is a list of prefabs, not a list of instantiated objects, you need to store the instance of the object and move that instance something like this
GameObject instanceClone;
instanceClone = Instantiate(Enemies[Random.Range(0f, 8f)], position, Quaternion.identity);
and move the instanceClone .