- Home /
How can I destroy many instantiated objects on endless game
I've created an endless game where there are instantiated many prefabs.I need to delete objects that player has passed some steps ago.I think the solution is to delete first 20 objects in editor,but I don't know how to write script for that,PLEASE HELP!!!!!
Answer by PerfectSkies · Mar 20, 2019 at 05:22 PM
Here is my script that I used:
public GameObject StructureToSpawn;
GameObject spawnedStructure;
GameObject prevStructure;
private Vector3 StartPositionForStructures;
void Start()
{
StartPositionForStructures = new Vector3(-30f, 0f, 0f);
//Start postion should be outside screen.
SpawnStructure();
}
//The Spawn Part
void SpawnStructure() //AtStart
{
spawnedStructure = GameObject.Instantiate(StructureToSpawn,
StartPositionForStructures, startRotation) as GameObject;
prevStructure = spawnedStructure;
}
//The Destroy and Respawn Part
void InstanciateStructure() //On update
{
if (spawnedStructure.transform.position.x < -35f) //When struct outside screen
{
prevStructure = spawnedStructure;
spawnedStructure = GameObject.Instantiate(StructureToSpawn, StartPositionForStructures, startRotation) as GameObject;
Destroy(prevStructure);
//Or pool multiple objects into an array and destroy all...
}
}
void Update()
{
InstanciateStructure();
spawnedStructure.transform.Translate(Vector3.left * 15f * Time.smoothDeltaTime);
}
Yes I'm in Unity2D.One object is moving and camera with him.The other instantiated objects are not moving.I need to delete instantiated objects,because they are a lot.
You should really pool the objects. Disable them when you don't need them anymore and then move them to where you are instantiating new versions rather than creating more.
I've edited my answer, hope it helps...
Your answer
Follow this Question
Related Questions
Random instantiation endlessly? 1 Answer
2D destroyer moves 0 Answers
How to detect a single collision when 2 identical gameobjects collide. 1 Answer