- Home /
Trash Collection For Instantiated Game Object
Hi. I have already posted something like this but this one is different. In my game the player is climbing up a wall of infinitely instantiated brick walls. A wall is deleted when a certain distance from the player. The only problem is that it only destroy the one wall I've assigned it to. How can I make it destroy any game object with the tag "wall" that is a certain distance away. Here is my code now:
using UnityEngine;
using System.Collections;
public class BrickWallTrashCollection : MonoBehaviour {
public GameObject wall;
public Transform player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if( Vector3.Distance( wall.transform.position, player.position ) >= 10f ){
Destroy( wall );
}
}
}
Please help. Thanks!
Answer by ahmedbenlakhdhar · Dec 11, 2014 at 01:41 AM
You may retrieve all the game objects having the given tag and stock them in an array, like this:
GameObject[] walls;
void Start(){
walls = GameObject.FindGameObjectsWithTag("wall");
}
Then you check for each one if it is far from the player:
foreach(GameObject wall in walls){
if(wall!=null && Vector3.Distance(wall.transform.position, player.position)>=10f){
Destroy( wall );
}
}
@ahmedbenlakhdhar Hi. This works except it stops deleting the walls when all of the original walls are gone and only instantiated only ones are left. Why is this?
Because the array walls
is populated in Start
(only for one frame).
Try to populate it at each frame by using it in Update
ins$$anonymous$$d.
void Update(){
walls = GameObject.FindGameObjectsWithTag("wall");
foreach(GameObject wall in walls){
if(wall!=null && Vector3.Distance(wall.transform.position, player.position)>=10f){
Destroy( wall );
}
}
}
@ahmedbenlakhdhar Thank you so much! Everything works!!
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
A node in a childnode? 1 Answer
FPS Object-on-wall Placement 0 Answers
Destroy doesn't work when also instantiating new objects 1 Answer
Destroy the current GameObject? 7 Answers