首页 > 解决方案 > 如何从 Unity 中的另一个脚本中获取对撞机被击中的次数

问题描述

我想计算与碰撞器的碰撞次数,从现在开始我该怎么做?

检测标志.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();
        }
    }
}

标签: c#unity3dcountcollider

解决方案


您可以在 Collision2D 对象上使用 GetContacts 方法,然后存储这些值,或者只是存储方法调用中的碰撞计数,这显然是简单的解决方案,虽然它可能不是最好的解决方案,但来自您的其他评论这似乎是你想要做的。

当我进入实际桌面时,可能会在稍后使用更好的替代方案 + 代码示例来更新它。


推荐阅读