Hello, I’m trying to make a melee system for my game. I put an empty game object with a box collider around my player and a bit in front of him. When I walk into the enemy that I tagged enemy, it doesn’t detect it. It does detect me at the beginining of the game though. Here’s my code.
#pragma strict
var damage = 50;
var canHitEnemy = false;
function Update()
{
if (Input.GetButton("Fire1"))
{
if (canHitEnemy == true)
{
AttackEnemy();
}
}
}
function OnTriggerEnter(theCollider : Collider)
{
if(theCollider.gameObject.tag == "Enemy")
{
Debug.Log("Enemy Trigger Enter.");
canHitEnemy = true;
}
}
function OnTriggerExit(theCollider : Collider)
{
if(theCollider.tag == "Enemy")
{
Debug.Log("Enemy Trigger Exit.");
canHitEnemy = false;
}
}
function AttackEnemy()
{
yield WaitForSeconds(2);
Debug.Log("Enemy Attcked");
}
Thanks in advanced.
Have you set it up as a trigger?
At least one of the two objects have to have a rigid body component for the trigger event to happen. And it’s recommended that all moving objects have rigid bodies on them.
1 Like
Nope, that didn’t change anything either. 
What kind of melee attack? What is hitting what? A fist, sword what objects?
To elaborate on this, there are certain requirements that also need to be met. Take a look at http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html
Specifically the Collision action matrix at the bottom is of interest.
I had a very similar problem and solved it by adding a box collider instead of a sphere collider. Im not sure why or how it worked but it did maybe it could work for you…
I have the same Problem. My both GameObjects (cars), have Children the BoxCollider. Both Parents (car) have a RigidBody and when they collide they dont recognize. Can anybody help??
Have you checked the tags? I’ve had the same problem and the only reason to that is because I had my character marked as ‘untagged’ when in my code I marked the collision to trigger when it hits an object with the ‘player’ tag. You could just check tags under the name of the object.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag(“Player”)) // ← THIS IS WHAT I MEANT BY THE TAGS
{
//player takes damage
other.GetComponent().health -= damage;
Debug.Log(other.GetComponent().health);
Destroy(gameObject);
}
}
Since the code could be correct but you might have labeled your object wrong. [refer to comment above]
I found that my game objects in scene will lose their solid, ‘colliding’ effect by check-marking ‘Is Trigger’ in the target object… it’s two years later, hopefully you figured it out by now