- Home /
On TriggerEnter issues
Hello, so I've just started to make my 2D space shooter game and I'm working on shooting the enemies. Such an easy task I know, but I don't understand where I'm going wrong with it. Here's my code attached to my bullet prefab (bullet is a trigger) that deals with triggers:
function OnTriggerEnter(otherObject: Collider)
{
if(otherObject.gameObject.tag == "Enemy")
{
print("Hit");
Destroy(gameObject);
otherObject.GetComponent(EnemyScript).life -= 1;
}
}
I've made sure my Enemy is tagged as "Enemy", and it is a trigger. I'm not sure what's wrong with this, but it probably just needs a new pair of eyes. Also, I have the "print()" there to tell me if there is collision. Thank you for all your help.
How fast is the bullet going? It may be passed the collider the next time it updates the trigger events. If thats the problem you can always use a Raycast forward 1 gameUnit(or to ur scale) to detect events that may get overlooked.
Other things here...When you use Destroy() it should be called last(since you destroy this object thats running the code) therefore the EnemyScript.life.... may never be called since you destroy the script the line before. Also the condition can be cleaned up as such
if(otherObject.CompareTag("Enemy")) //run code
tag is also a member of collider so you could do away with gameObject portion of the condition.
Your comment gave me an idea of putting a Rigidbody onto the bullet, fortunately, that was the solution. Thank you very much for your comment, it helped a lot.
Oh, good deal. Glad you got some inspiration from that. Cheers
Answer by timo0060 · Jul 09, 2012 at 02:14 AM
I just had to add a Rigidbody onto my bullet. I knew it was something simple that I overlooked.