eichan114
eichan114

Reputation: 69

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();
        }
    }
}

Upvotes: 1

Views: 539

Answers (2)

Art Zolina III
Art Zolina III

Reputation: 507

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();}
    }
}

Upvotes: 1

A Sad Shoe
A Sad Shoe

Reputation: 144

You can use the GetContacts method on your Collision2D object, and then store those values, or simply store the collisions count from the method call, this is obviously the simple solution, although it probably isn't the best solution, but from your other comment it seems like it's what you want to do.

Might update this later with a better alternative + a code example when I get to an actual desktop.

Upvotes: 1

Related Questions