Destroying object on impact.

Hello, I am currently creating a small game in unity for a school project, and I have a small question for an error that's occured.

I have created a soldier, and I want him to have a knife, so he can stab his enemies. to do this, I created an invisible collider infront of him, which follows him around. On this collider, I added this code:

function OnTriggerEnter(obj:Collider)
{
    if(Input.GetKeyDown("E"))
    {
        print(123123);
        if(obj.gameObject.tag == "Enemy")
        {
            //Enemy.Life = 0;
            print("TAGGED");
        }
    }
}

As you see, there's a print to write out if I collide with the enemy (yes, I have an object on the scene both named and tagged as "Enemy") But when I collide with it and hit the button E, nothing appears. I wonder if anyone of you might know the solution to this. Thanks in advance. :)

Please edit your post and format your code correctly using the code formatting option. You'll get a better response to your question that way.

Yeah ;) i've done it for you, but for future posts take the time to format your question the right way.

1 Answer

1

OnTriggerEnter is called just one time when the enemy enters your trigger area.

Try OnTriggerStay().

You version have two one frame events cascaded... So you can only stab him when the enemy enters the trigger and you press E within the same frame :D


edit

var targetEnemy : GameObject;

function OnTriggerEnter(obj:Collider)
{
    if(obj.gameObject.tag == "Enemy")
    {
        targetEnemy = obj.gameObject;
    }
}

function OnTriggerLeave(obj:Collider)
{
    if(obj.gameObject == targetEnemy)
    {
        targetEnemy = null;
    }
}

function Update()
{
    if(Input.GetKeyDown("E"))
    {
        if(targetEnemy != null)
        {
            //Enemy.Life = 0;
            print("stabbed");
        }
    }
}

That should work, but if multiple enemies enters your trigger only the last one can be stabbed ;)

Well, the problem i see here is that OnTriggerStay isn't executed every frams and therefore it's random if Input.OnKeyDown returns true or not...

Here's a solution ;)

Make sure that you don't use meshcolliders for detecting the enemy. Maybe try to add a rigidbody (iskinematic = true)