Home > Mobile >  how do i make sword work with enemy collider
how do i make sword work with enemy collider

Time:04-24

here is my current code:

public GameObject enemy;


void OnCollisionEnter(UnityEngine.Collision collisionInfo)
{
    if (collisionInfo.collider.tag == "sword")
    {
        Debug.Log("works");
        enemy.SetActive(false);

    }
    else
    {
        Debug.Log("doesnt work");
    }
}

i have attached this to the enemy and also i tried a different script attached to the sword

 void OnTriggerStay(Collider col)
{
    if (Input.GetButtonDown("Fire1"))
    {

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

            Destroy(col.gameObject);
        }
    }
}

both codes don't work, it seems that the problem isnt with the sword collision cus i have also added the tag to another gameobject and it doesnt work. i looked online but havent found anything that works so fat

CodePudding user response:

update: it seems that i have forgot you need a rigid body for collision detection. simple mistake but it made my code not work!

CodePudding user response:

For collision enter to work, both the sword and the enemy colliders need to have the "IsTrigger" box unticked.

For on triggerstay is the opposite, both need to have that box ticked.

Basically, Triggers do not collide they call that OnTriggerEnter function, while non-triggers use the OnCollisionEnter.

  • Related