如果 - 陈述没有被观察到

时间:2018-05-25 12:53:46

标签: c# unity3d

在我的Unity项目中,我有一个附加到几个预制件的脚本。每隔几秒钟产生一个随机预制件。这是我附加脚本的一部分:

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.transform.CompareTag("ground"))
    {
        if (transform.gameObject.name == "FallingKeule(Clone)") 
        {
            Destroy(transform.gameObject);
        }
        if (transform.gameObject.name == "FallingHeart(Clone)")
        {
            Destroy(transform.gameObject);
        }
        if (transform.gameObject.name == "FallingCup(Clone)")
        {
            Destroy(transform.gameObject);
        }
        else
        {
            print("You lost a life!");
            Player.GetComponent<Colliding>().LostLife();
            Destroy(transform.gameObject);
        }               
    }
}

如果一个游戏对象是随机产生的并且它击中了地面,那么它就是“FallingKeule(Clone)” - &gt; “(克隆)”因为预制件是通过它来实现的,而不是

if (transform.gameObject.name == "FallingKeule(Clone)") 

没有完成! else代码已经完成:

else
{
    print("You lost a life!");
    Player.GetComponent<Colliding>().LostLife();
    Destroy(transform.gameObject);
}

1 个答案:

答案 0 :(得分:3)

您应该使用else if声明:

if (transform.gameObject.name == "FallingKeule(Clone)") 
{
    Destroy(transform.gameObject);
}
else if (transform.gameObject.name == "FallingHeart(Clone)")
{
    Destroy(transform.gameObject);
}
else if (transform.gameObject.name == "FallingCup(Clone)")
{
    Destroy(transform.gameObject);
}
else
{
    print("You lost a life!");
    Player.GetComponent<Colliding>().Destroy(transform.gameObject);
}

或更好:

var gameObjectName = transform.gameObject.name;
if(gameObjectName == "FallingKeule(Clone)" || gameObjectName == "FallingHeart(Clone)" || gameObjectName == "FallingCup(Clone)")
{
    Destroy(transform.gameObject);
}
else
{
    print("You lost a life!");
    Player.GetComponent<Colliding>().Destroy(transform.gameObject);
}

甚至:

string[] dObjects = new string[] { "FallingKeule(Clone)", "FallingHeart(Clone)", "FallingCup(Clone)" };

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.transform.CompareTag("ground"))
    {
        if(dObjects.Contains(transform.gameObject.name))
        {
            Destroy(transform.gameObject);
        }
        else
        {
            print("You lost a life!");
            Player.GetComponent<Colliding>().Destroy(transform.gameObject);
        }
    }
}