- Home /
The question is answered, right answer was accepted
Why won't this object destroy?
I have the script set up so when my player collides into the coin it should dissapear and be destroyed. (this code is attached to the coin)
void OnTriggerEnter(Collider myTrigger){
if (myTrigger.gameObject.name == "Player"){
Destroy(gameObject);
PlayerScript.coin_total += 1;
}
}
The coin is instantiated after a monster is killed in this code attached to the monster game object. Basically when it gets hit by a bullet he will be destroyed and drop a coin.
void OnTriggerEnter(Collider myTrigger){
if (myTrigger.gameObject.name == "Bullet(Clone)"){
Destroy(gameObject);
Instantiate(coin, transform.position, transform.rotation);
}
}
The monster gets destroyed and drops the coin just fine, but when the player collides with it, it doesn't disappear or add to his coin count. I found that if a monster is colliding with the player while he's colliding with the coin it works, but I don't know why. I'm assuming it's because I'm initiating the coin from the monster's script. But if that's the case I don't know why my bullets work fine when they're initiated from the Player's script.
Have you tried to debug it? Does the OnTriggerEnter from your first sample is even called?
Besides - googling for 'Unity OnTriggerEnter', brought me some interesting entries. I believe that reading first two of them, found in Unity Answers will help a lot.
Solved it......
ok well i'm an idiot I needed to add a rigidbody to my player
I'm dumb my bad.
Answer by YoungDeveloper · Aug 10, 2013 at 08:42 PM
Destroy(myTrigger.gameObject); ?
According to the op script is attached to the coin, so this would destroy player :)
Wasn't sure what should destroy what, if so then:
Destroy(this.gameObject);
Tried this, it does the same thing and only deletes if i'm also colliding with the monster. Otherwise I just run over the coin and nothing happens x.x
Then ins$$anonymous$$d of checking the collision in each coin, you can set one collision check on player itself.
void OnControllerColliderHit(ControllerColliderHit hit) {
if(hit.gameObject.tag == "Coin"){
Destroy(hit.gameObject);
PlayerScript.coin_total += 1;
}
}
//For this you must add a tag for the coin called "Coin".
By the way, shouldn't it be gameObject.tag, ins$$anonymous$$d of your gameObject.name, because your checking tag.
I was checking the name not the tag, also I just tried your code and it didn't work.