[英]If-Statement hadn't been obeserved
in my Unity project I have a script attached to a couple of prefabs. 在我的Unity项目中,我有一个脚本附加到几个预制件上。 Every few seconds a random prefab is spawned.
每隔几秒钟会生成一个随机的预制件。 This is a part of my attached script:
这是我所附脚本的一部分:
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);
}
}
}
If a GameObject is spawned by random and it hit's the ground, and it is a "FallingKeule(Clone)" --> "(Clone)" because the prefab is cloned by it's initalisation the Code from 如果一个GameObject是随机生成的,并且它是地面,并且它是一个“ FallingKeule(Clone)”->“(Clone)”,因为预制件是通过它的初始化而克隆的
if (transform.gameObject.name == "FallingKeule(Clone)")
isn't be done! 还没完成! The else code is been done:
else代码已完成:
else
{
print("You lost a life!");
Player.GetComponent<Colliding>().LostLife();
Destroy(transform.gameObject);
}
You should use else if
statement: 您应该使用
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);
}
or much better: 或更好:
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);
}
or even: 甚至:
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.