【发布时间】:2019-05-31 18:59:06
【问题描述】:
部分代码有效 (hp1 -= damage1;),但第二部分无效。
我哪里做错了?
以下是两个脚本的一部分:
Player1.cs
private Bullet1 b1;
void Start()
{
b1 = FindObjectOfType<Bullet1>();
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Bullet1")
{
hp1 -= damage1; // it works, my player loses hp
Destroy1(); // doesn't work
}
}
void Destroy1()
{
b1.hit1 = true; // hit for bullet1.cs
}
Bullet1.cs
public bool hit1;
void Update()
{
if (hit1)
{
hit1 = false;
Destroy(gameObject);
}
}
如果我在 Unity 中实时切换bool hit = true,会破坏作品。表示Bullet1.cs收不到hit = true;
如果我交换线 hp1 -= damage1; 和 Destroy1();,我的玩家不会受到伤害。因此,Destroy1(); 停止了我的代码,然后无法激活其他行。此外,如果我将Destroy1(); 更改为b1.hit1 = true;,则不会发生任何新情况。
【问题讨论】:
-
出现这种情况时控制台是否有错误?可能是空引用异常?如果是这样,我们将需要查看该错误。
-
听起来
b1对我来说是空的。你不是在检查那个。 -
在您的播放器开始时,您正在获取对子弹对象的引用,但随后在您的子弹对象中您销毁了子弹。你的代码逻辑很奇怪。相反,您应该直接通过碰撞检测调用来摧毁子弹。将
Destroy(col.gameobject)放在播放器的碰撞检测中,而不是用布尔值做任何事情。 -
@AlexMyers 1)
NullReferenceException: Object reference not set to an instance of an object PlayerController.Destroy2 () (at Assets/Scripts/Game/PlayerController.cs:255) PlayerController.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Scripts/Game/PlayerController.cs:116)2)NullReferenceException: Object reference not set to an instance of an object PlayerController.Destroy2 () (at Assets/Scripts/Game/PlayerController.cs:255) -
254-256:
void Destroy2() { b2.hit2 = true; }