- Home /
Trash Collection for Instantiated Objects
Hi. I know I recently posted a question similar to this, but please ignore that one. It did not provide sufficient detail. Here is the new version. Anyways, in my game the player is climbing up infinitely instantiated walls. I want to delete the walls that are no longer needed. Here is the code I have so far:
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(wall.transform.position = Vector3.Distance(player.position.x + 10, player.position.y +10){
Destroy(wall.gameObject);
}
}
}
I get an error on the open bracket right after the if statement at the end. It tells me that this was an unexpected symbol. I know there are multiple things wrong with this code so can somebody please point me in the right direction? Thanks!
Answer by theLucre · Dec 09, 2014 at 02:37 AM
A few things:
When comparing values, use the == operator, not a single =
You are comparing Vector3 and float values in your if statement, which is not possible.
The wall property you have is already a GameObject, so you don't need to use wall.gameObject.
Instead try this, where you set a distance value in float units, and the wall will be destroyed when closer than that distance in 3D space. Be sure to stop using the wall reference after you destroy it.
if( Vector3.Distance( wall.transform.position, player.position ) <= SomeDistance )
Destroy( wall );
Or if you're specifically comparing X only:
if( wall.transform.position.x >= player.position.x - 10 ||
wall.transform.position.x <= player.position.x + 10 )
Destroy( wall );
@theLucre Sorry I am a beginner/intermediate coder so would I fill in a point for SomeDistance or what?
Not a Vector point, but a float number. It would be the number of units the player is from the Wall when it would be destroyed.
@theLucre Hi. I used your first suggestion of code and it works fine but the problem is that it destroys walls that the player has not reached yet. How can I make it only destroy walls under the player?
@theLucre Sorry with all the questions but how can I make it destroy any game object with the tag "Wall" ins$$anonymous$$d of it only destroying the wall that has been assigned to the wall game object?
Your answer
![](https://koobas.hobune.stream/wayback/20220613173600im_/https://answers.unity.com/themes/thub/images/avi.jpg)