【发布时间】:2020-08-25 08:26:46
【问题描述】:
好的,这就是正在发生的事情 我有这个带有“ApplyForce”方法的“Bullet”脚本,附加到 Bullet 预制件
public void ApplyForce (Vector2 direction)
{
const float magnitude = 5f;
GetComponent<Rigidbody2D>().AddForce(magnitude * direction, ForceMode2D.Impulse);
}
还有一个“Ship”脚本,该脚本将实例化一个 Bullet 并尝试访问其“Bullet”组件,然后访问“ApplyForce”方法以在船面向的同一方向上施加力
// check for shooting input (left ctrl key) and fire
if (Input.GetKeyDown(KeyCode.LeftControl))
{
GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.GetComponent<Bullet>().ApplyForce(thrustDirection);
}
问题是,它不起作用。它发送此错误:
NullReferenceException:对象引用未设置为对象的实例 Ship.Update () (在 Assets/scripts/Ship.cs:56)
我知道我的问题是如何正确访问新实例化的游戏对象,但我找不到合适的方法来做到这一点。所以在这里我请求你的帮助。
对于任何可能激怒您的新手错误,我深表歉意,因为我对编码/编程还很陌生,并且对此几乎没有经验
【问题讨论】:
-
基本的 C# 方式是
bullet.ApplyForce(thrustDirection);,它在 Unity 中的工作方式应该相同。