Instantiating gameObjects, adding them to a list then moving every gameObject in the list.,Moving gameobjects in gameobject list
Hi, I'm new to Unity and working on a game where the player moves infinitely in one direction (I have the terrain moving endlessly towards the player) and want to spawn obstacles (rocks) for the player to avoid. At the moment, I am instantiating the prefabs, adding them to a gameObject list, then, in the update method, moving every gameObject in the list along the z axis. There are no compiler errors, but when I run the game, a rock spawns but does not move at all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstacleGenerator : MonoBehaviour
{
private List<GameObject> currentObstacles = new List<GameObject>();
public GameObject[] terrainChunks = new GameObject[5];
private GameObject currentTerrainChunk;
private float spawnX = 0;
private float spawnZ = 40;
public GameObject obstacle;
private bool spawnObject = true;
private float terrainLength;
private float terrainSpeed;
private GameObject[] terrainPieces;
void Start()
{
EndlessTerrain endlessTerrain = gameObject.GetComponent<EndlessTerrain>();
terrainLength = endlessTerrain.terrainLength;
terrainSpeed = endlessTerrain.terrainSpeed;
terrainPieces = endlessTerrain.terrainPieces;
}
void Update()
{
if (spawnObject)
{
spawnObject = false;
Instantiate(obstacle, new Vector3(0,0,0), Quaternion.identity);
currentObstacles.Add(obstacle);
}
foreach(GameObject obstacle in currentObstacles)
{
Vector3 newObstaclePosition = obstacle.transform.position;
newObstaclePosition.z -= terrainSpeed * Time.deltaTime;
if (newObstaclePosition.z < -terrainLength * 2)
{
newObstaclePosition.z += terrainLength * terrainPieces.Length;
}
obstacle.transform.position = newObstaclePosition;
}
}
}
If anyone can offer any ideas as to what I have done wrong, then any help is appreciated. Thanks.
Your answer
Follow this Question
Related Questions
Having trouble with instantiating bullets at multiple points via a list of transforms. 1 Answer
Instantiate duplicate of inactive child in GameObject 0 Answers
Instantiated objects can't convert to GameObjects 0 Answers
NullException Error while instantiating gameobjects 0 Answers
Check if a large number of gameobjects are colliding 1 Answer