涂鸦跳团结c#

-1 c# unity-game-engine

所以看:我在游戏中有一个怪物,当玩家与他发生碰撞时,会出现一个面板并说再试一次.现在有一个盾牌对象,可以保护玩家免于死亡,所以当玩家与它发生碰撞然后如果你触摸怪物你不应该死一次:就像那样,你触摸盾牌和你免受一人死亡.你能帮我写这段代码吗?

public GameObject panel;
public bool hasShield = false; /* no shield in the beginning */    

void OnCollisionEnter(Collision col)
{
    if(col.gameObject.tag == "Shield") 
    {
        hasShield = true; //We are safe now.
        /* TODO: StartCoroutine() or Invoke() to reset the variable and the graphic effect after some amount of time. */
    }
    else if (col.gameObject.tag == "Monster" && !hasShield) 
    { 
        //We hit a monster and had no shield. Display gameover.
        panel.SetActive (true);
    }
    //I assume the panel is inactive by default so no need to call SetActive(false) on it.
}
Run Code Online (Sandbox Code Playgroud)

Max*_*rdt 5

永远无法达到此代码的内部:

     if (col.gameObject.tag == "Shield") 
    {
        if(col.gameObject.tag == "Monster")
        {
            panel.SetActive(false);
        }
    }
Run Code Online (Sandbox Code Playgroud)

对于第一次if检查,标签必须是"盾牌",但是对于第二次测试,它必须是"怪物".这两个条件不能同时为真,代码相当于

 if(col.gameObject.tag == "Shield" && col.gameObject.tag == "Monster")
Run Code Online (Sandbox Code Playgroud)

但是,如果在上面的表达式中替换&&||(逻辑OR),您将获得所需的结果.所以,重写的代码将是

    if (col.gameObject.tag == "Monster") 
    { 
        panel.SetActive (true);
    }
    if (col.gameObject.tag == "Shield" || col.gameObject.tag == "Monster") 
    {
         panel.SetActive(false);
    }
Run Code Online (Sandbox Code Playgroud)

如果是"盾牌" "怪物" ,内部代码现在将触发.

编辑:正如我们在评论中谈到的那样,逻辑总体上存在缺陷.现在根据你的描述

我触摸怪物后需要激活面板,但是如果我触摸盾牌然后触摸怪物,则面板不应该出现

我建议如下:当收集盾牌时,将其保存到某个变量中,例如

bool hasShield;
Run Code Online (Sandbox Code Playgroud)

true在收集盾牌时将其设置为.然后,如果你击中某个东西,检查它是否是一个怪物,如果你没有盾牌,那么你会看到"游戏结束"屏幕.所以玩家应该看起来像

    public GameObject panel;
    public bool hasShield = false; /* no shield in the beginning */    

    void OnCollisionEnter(Collision col)
    {
        if(col.gameObject.tag == "Shield") 
        {
             hasShield = true; //We are safe now.
             /* TODO: StartCoroutine() or Invoke() to reset the variable and the graphic effect after some amount of time. */
        }
        else if (col.gameObject.tag == "Monster") 
        { 
            if(!hasShield)
                panel.SetActive (true);  //We hit a monster and had no shield. Display gameover.

            else
                hasShield = false; //loose the shield
        }
        //I assume the panel is inactive by default so no need to call SetActive(false) on it.
    } 
Run Code Online (Sandbox Code Playgroud)