- Home /
Why does Destroy(this.gameObject) destroys a prefab that got nothing to do with the script
Hi everyone, i'm instantiating prefabs from a controller object with this script
void Update () {
timeLeft -= Time.deltaTime;
if (timeLeft < 0) {
timeLeft = totalTime;
int random = Random.Range(0, locations.Length);
SpriteRenderer wood;
for(int i = 0; i < locations.Length; i++)
if(i != random)
wood = Instantiate (wood_prefab, new Vector3 (locations[i], 4, 0), transform.rotation) as SpriteRenderer;
}
}
The prefabs have a box 2d collider attach and my main object has a box collider 2d and a rigidbody2d, so im detecting collision between those objects withe OnCollisionEnter2d() function, i have my function like this.
void OnCollisionEnter2D(Collision2D coll) {
Destroy (this.gameObject);
}
It detects the collsiions just fine, but when the Destroy() func is call, its also destroys a random prefab in the world I also have this behaviour for the prefab, do know if it has something to do
// Update is called once per frame
void Update () {
//wood position
Vector3 currentPosition = transform.position;
//move toward
Vector3 moveToward = new Vector3 (transform.position.x, transform.position.y - 1, 0);
transform.position = Vector3.Lerp( currentPosition, moveToward, Time.deltaTime );
if (transform.position.y < -6)
Destroy (this.gameObject);
}
Hope someone can help me, Thanks in advance!!! =)
Did you checked if the script which has void OnCollisionEnter2D(Collision2D coll) { Destroy (this.gameObject); }
isnt atached to another GameObjects so that's why they got deleted as well?
To test, before each destroy, add something like Debug.Log("I am "+transform.name + " destroying: " +this.transform.name");
And ins$$anonymous$$d of destroying, make the object twice as tall, or turn red. Then you can Pause, check collision boxes ... try to figure out why A thinks it hit B.
Hehe thanks a lot, it was a weird bug but i forgot that i can pause the game and check the items, so i found my "wood" prefab hide behind the background, i don't know why, its sorting layer and order in the layer doesn't change, but thanks a lot for the help =)
Your answer
Follow this Question
Related Questions
Collision detected but destroy not working 2 Answers
How to make a little wiggle room for the collision? 1 Answer
Fixing an inconsistent 2D collision 0 Answers
Character Hit Animation play endlessly 2 Answers
2D colliders not working with UI? 0 Answers