Search code examples
unity-game-engineunityscript

Mouse Click inside OnTriggerEnter


Video URL for easy understanding - http://tinypic.com/r/28jdyyq/9

In this video, you can see my problem, when the sword touches the enemy.. enemy gets destroyed.. But i want when i mouseclick (or hit), then only ..enemy should destroy..

void OnTriggerEnter(Collider col)
    {
        if (col.GetComponent<Collider>().tag == "enemy")
        {
            Destroy(col.gameObject);

        }
    }

This is my code, i have enemy and Player with sword (with collider) , everything is perfect, i want when i click mousebutton then only sword should kill enemy,

But, What is happening when i bring my player (with sword) near enemy and sword touches enemy, it is killing enemy without i hit by sword.

I tried the below code also by adding mouse click event inside Trigger , but nothing happens. Any idea Please

void OnTriggerEnter(Collider col)
    {

        if (Input.GetButtonDown("Fire1")){

                if (col.GetComponent<Collider>().tag == "enemy"){

                    Destroy(col.gameObject);
                }

        }

    }

Here is code for Swing -

 if (Input.GetButtonDown("Fire1"))
        {
            anim.SetTrigger("hit");
        }

Here hit is trigger in animation controller and make transition to the animation clip


Solution

  • you can use Animation Events to make true a Boolean when the sword rises in animation and turn it to false when the sword goes down and check that Boolean when OnTriggerEnter is called
    make a variable like hit set it to true and false via animation Event

    public bool hit;
    
    void OnTriggerEnter(Collider col)
        {
    
            if (hit){
    
                    if (col.GetComponent<Collider>().tag == "enemy"){
    
                        Destroy(col.gameObject);
                    }
    
            }