- Home /
Removing an object if it spawns in a building
In my game, I have it that when pick-ups are collected, a new one is made in a random location in the game space. However, sometimes this location is inside of a building, so the player cannot reach it. I have the following code on my buildings to that if anything with the tag respawn(the pick-ups) enter their collision box, they're destroyed, and a new one is made.
using UnityEngine; using System.Collections;
public class Building : MonoBehaviour
{
public GameObject parson;
void OnTriggerEnter (Collider other)
{
if(other.gameObject.tag == "Respawn")
{
Debug.Log ("In BUILDING");
Destroy(other);
GameObject newparson = Instantiate(parson, new Vector3(Random.Range(10,-35),921,Random.Range(267,310)), Quaternion.identity)as GameObject;
parson = newparson;
}
}
}
However, this sometimes lead to the creation of pick-ups that don't get collected(their supposed to follow the player, but these seem to stay put, and allow the player to constantly rack up points). I want it so that everytime a pick up is in a building, the pick up is removed, and a new one is created. Any help would be appreciated.
Yeah, $$anonymous$$arkFinn is correct. The line "Destroy(other)" is destroying the Collider component on that GameObject rather than the GameObject itself. Use the code $$anonymous$$arkFinn gave you and that should be good.
Also, it might be more useful to develop a spawn system that would prevent such things from happening, rather than dealing with the consequences.
Answer by MarkFinn · Dec 04, 2012 at 06:04 AM
I'm only guessing here, but could it be that you need to say
Destroy(other.gameObject);so that you're not only destroying the collider?
Only a guess...
Doing that seems to get me the following error when i try to pick up one spawned inside a building:
$$anonymous$$issingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
I have tried moving the piece of code which deletes the objects to the end of the code, but that doesn't seem to work. This also seems to destroy previously picked-up objects, which is something I don't want happening ><.
I'm not really getting what you want to happen in this situation. You spawn a pickup in an invalid location, delete it and then try to pick it up?
Something strange in your logic, or at least in my understanding of it.
I want it to remove the pick up, make a new one, and be able to pick the new one up.
However, last night I had an idea: What if ins$$anonymous$$d of destroying the pick-up, I just have it get moved again?
Turns out my late night code idea worked! by moving the object ins$$anonymous$$d of deleting it and then making a new one, I got objects that spawn in buildings spawning in a new location.
other.gameObject.transform.position = new Vector3(Random.Range(10,-35),921,Random.Range(267,310));
Thank you for the help!