I'm working on a game in which obstacles are Instantiated randomly 5 to 20 units ahead of the player.
When they are instantiated, I want to add them to a list so that when there are too many obstacles loaded in the game, it will remove them from the list and then delete them from the game.
I'm having trouble adding them to the list, because using obstacleList.Add(Obstacles.name);
doesn't work.
Here's my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Generate : MonoBehaviour{
//player position
public Transform Player;
// The prefab for an obstacle
public GameObject Obstacle;
// Holds float distance from 0 for each obstacle that is instantiated
private float nextObstacle = 30;
// is supposed to hold the names of all active instances of the obstacle prefab
List<string> obstacleList = new List<string>(10);
void FixedUpdate()
{
//Checks to see if the player is colser than 30 units to the most recently spawned obstacle
if (nextObstacle - Player.position.x < 30)
{
//Generates a new obstacle
GenerateObstacle();
}
}
void GenerateObstacle()
{
// Randomly assignes a number for horizontal and vertical Transform
int randH = Random.Range(5, 20);
int randV = Random.Range(1, 3);
//Instantiates an obstacle using those random values
Instantiate(Obstacle, new Vector3(nextObstacle + randH, randV, 0), Quaternion.identity);
//Makes that obstacle the new distance so a new obstacle can be spawned
nextObstacle += randH;
// Is supposed to add the name of the obstacle that was Instantiated to a list
obstacleList.Add(Obstacle.name);
//checks when list has more than 10 items in it
if (obstacleList.Count > 10)
{
DeleteObstacles();
// Removes the first item from the list
obstacleList.RemoveAt(0);
}
}
void DeleteObstacles()
{
// Supposed to destroy the copied prefab
Destroy(Obstacle);
}
}