- Home /
Need assistance with destroying Gameobjects
I am making a endless runner type game, having problem with destroying platforms once its off my screen. Just want to clean up my hierarchy panel. Here is my platform script....
public Transform PlatformPrefab; private Vector3 _nextTileSpawn; void Start() { _nextTileSpawn.z = 12; StartCoroutine(SpawnPlatform()); }
void Update() {
}
IEnumerator SpawnPlatform()
{
yield return new WaitForSeconds(0.5f);
Instantiate(PlatformPrefab, _nextTileSpawn, PlatformPrefab.rotation);
_nextTileSpawn.z += 4;
Instantiate(PlatformPrefab, _nextTileSpawn, PlatformPrefab.rotation);
_nextTileSpawn.z += 4;
StartCoroutine(SpawnPlatform());
}
}
I noticed that you are not actually destroying the game objects. What have you tried ? And why are you running the same 2 lines of code twice ? I can show you an example of how to write a simple script to do this, and you don't really need to use Coroutines. I feel a lot of people use them when starting out because it has the function WaitForSeconds(...), which is what most people want. The same can be achieved without Coroutines.
Answer by metalted · Feb 28 at 07:03 PM
This below is untested code, but i hope it gives you an idea of how to handle the problem. Instead of a coroutine i just used a timer to simplify things. The timer will run and each time the timer runs out we create a platform. When creating a platform we save a reference to it, so we are able to destroy it later. At the moment I used an arbitrary amount of maximum platforms. I hope the comments will help you out with anything that isn't clear. The most important part of this, is to save a reference to your created objects (in an array or list...), so you can access them later.
public Transform platformPrefab;
public Vector3 nextTileSpawn;
//A list to hold all the instantiated platforms.
public List<GameObject> activePlatforms = new List<GameObject>();
//How many platforms can be active at once?
public int maxPlatforms = 3;
//Timer
public float timerValue = 0.0f;
public float timerMax = 0.5f;
public void Start()
{
//Some conditions here...
gameRunning = true;
}
public void Update()
{
//Increment the timer
timerValue += Time.deltaTime;
//Has the timer expired?
if(timerValue >= timerMax)
{
//Reset the timer
timerValue = 0;
CreatePlatform();
}
}
public void CreatePlatform()
{
//First create a new platform and add it to the list.
activePlatforms.Add(Instantiate(platformPrefab, nextTileSpawn, Quaternion.identity));
//Increment the position for the next tile.
nextTileSpawn.z += 4;
//Check how many tiles are active now, if more than allowed, remove the oldest one.
if(activePlatforms.Count > maxPlatforms)
{
//To many platforms, remove the first one.
GameObject p = activePlatforms[0];
//Remove from the list.
activePlatforms.RemoveAt(0);
//Destroy the object.
Destroy(p);
}
}
Your answer
