【问题标题】:How to get the number of times the collider was hit from another script in Unity如何从Unity中的另一个脚本中获取对撞机的命中次数
【发布时间】:2021-10-10 23:41:24
【问题描述】:

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

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

【问题讨论】:

  • 你听说过Observer Pattern吗?
  • @nIcEcOw 我从未听说过。如果可能的话,我想在这两个脚本中解决它。

标签: c# unity3d count collider


【解决方案1】:

这里可以直接制作。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-14
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多