【发布时间】:2018-09-26 13:15:07
【问题描述】:
我收到上述错误,我尝试使用 debug.log 打印错误所在。 我正在创建一种坦克 obj。这会触发一些实例化的 obj。实例化的对象是攻击者。
在更新中,我使用 foreach 循环遍历所有实例化对象。如果找到并且如果对象在射程内。
void Update () {
if (attacker!= null )
{
//Debug.Log("inside att");
attacker = FindObjectsOfType<Attacker>();
}
// fire only if attacker is in range
if (IfInRange() && attacker!= null && running)
{
faceTowardTarget();
Fire();
}
}
bool IfInRange()
{// run through all the instantiated attacker
foreach (Attacker currentAttacker in attacker)
这工作正常,但上面给出了一些东西。在控制台的最后,循环继续进行,并且 currentAttacker 最终为空。我试图在控制台中打印它。但它不会出现在其他 if 语句中
{ //if attacker is in range
if (attacker != null )
{
Debug.Log(currentAttacker.GetComponent<Health>().isAlive);
if (Vector2.Distance(transform.position, currentAttacker.transform.position) < minDistance)
{
attackerPos = currentAttacker.transform;
return true;
}
}
if (currentAttacker == null)
{
Debug.Log("curre Attacker null");
running = false;
return false;
}
}return false;
}
攻击者有一个简单的生命值脚本,可以处理被射弹击中时造成的伤害。
Void update()
{
if (health <= 0)
{
**is there any better way to destroy an obj. If i destroy gameObject that error appear and it get stuck in foreach loop**
// Destroy(gameObject);
noOfKilled++;
isAlive = false;
scoreHolder.addScore(scoreValue);
}
}
非常感谢您的帮助。我尝试搜索但无法解决此问题。
【问题讨论】:
-
你能发布整个堆栈跟踪吗?
-
好吧,你有很多自高自大的逻辑。在您的
Update()、if检查中,交换IsInRange()和attacker != null。如果没有,您将使用null攻击者(可能)进入IsInRange()。现在,您可以删除IsInRange()中的攻击者空检查,这可能会使您的foreach循环弹出。此外,currentAttacker不会为空,它不会出现在您的列表中。你需要维护一个标志 -
非常感谢您找出错误。谢谢,游戏开发是我这辈子唯一想做的事。没有你们的帮助,我做不到。因为一个人做所有的事情真的有点困难。谢谢。
-
@jiveturkey 感谢 jiveturkey 的帮助。在你的帮助下,我能够制作我的第三场比赛。我在描述中提到了你的名字,希望你不介意。 lifeisjourney.itch.io/snowman
-
非常感谢您的赞誉。