Search code examples
c#unity-game-enginecountcollider

How to get the number of times the collider was hit from another script in Unity


I want to count the number of collisions with colliders, how do I do this from now on?

detectflags.cs

public bool IsReceive=false;
public void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.CompareTag("MolotovCocktail"))
    {
        IsAttack.Value = true;
    }

    if (other.gameObject.CompareTag("Weapon")||other.gameObject.CompareTag("MolotovCocktail"))
    {
        IsReceive = true;
    }
}

CountNumber.cs

public GameObject slimeChild;
private void GamaOverDecision()
{
    if (slimeChild.GetComponent<ChildrenSlimeWeaponCollider>().IsReceive == true)
    {
        var SlimeCount = 0;
        ++SlimeCount;
        if (SlimeCount == 5)
        {
            gameOverPopUp.GetComponent<GameOverPopUp>().SetView();
        }
    }
}

Solution

  • you can directly make it here.

    public bool IsReceive=false;
    public int slimCount;
    public void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("MolotovCocktail"))
        {
            IsAttack.Value = true;
        }
    
        if (other.gameObject.CompareTag("Weapon")||other.gameObject.CompareTag("MolotovCocktail"))
        {
            IsReceive = true;
    slimCount++
    if(slimcount == 5){ doSomething();}
        }
    }