- Home /
handling collision with two objects of the same tag
I have an object set up for collisions using
OnTriggerEnter(Collider other)
{
if (other.tag == "Bullet")
{
health -=10;
}
}
the problem I seem to be encountering is that when two "Bullet"s hit the object at the same time, it doesn't register the hit. maybe im missing something fundamental here?
thanks
Please let me know if my answer has provided the proper solution.
well, somehow this question was duplicated, ill mark you up, but I used the other guys solution :)
Answer by clunk47 · Jul 24, 2013 at 02:43 AM
Why not use a script on the bullet objects with the OnTrigger function? Say your player has a script called "Health", and you bullet has a script called "Bullet" for examples sake.
//Health.cs
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour
{
public int health = 100;
void Update()
{
if(health <= 0)
{
//Code for dying
}
}
}
Then your bullet script could call the component Health on your player, and decrease the health when it hits.
//Bullet.cs
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour
{
int damage = 10;
void OnTriggerEnter(Collider other)
{
if(other.collider.tag == "Player")
{
other.collider.gameObject.GetComponent<Health>().health -= damage;
}
}
}
NOTE: If your bullets are rigidbodies, be sure to set their collision detection to Continuous Dynamic. Any rigidbodies these bullets hit should be set to Continuous. Also, disabling gravity on the bullets will help them fly, just in case you had other issues.
A better way to go about this though, as far as I know, would be to use raycasting on the bullets.
Your answer
Follow this Question
Related Questions
handling collision with two objects of the same tag 1 Answer
How to speed up? 3 Answers
Problem with collision - Collision.other.gameObject is obsolete 1 Answer
Help With Colliders 3 Answers
Advice for Intersecting Colliders 0 Answers