我正在学习unity3D我创造了一个简单的游戏,玩家需要射击从天而降的敌人。我已经做了所有的事情但是当我尝试拍摄玩家在屏幕上点击的地方时我得到了这个错误NullReferenceException:对象引用未设置为对象的实例。有趣的是,这是朝向点击射击球,但由于例外,游戏突然退出。我将此代码附加到我的播放器:
if(Input.GetMouseButtonDown(0)){
shootDirection = Input.mousePosition;
shootDirection.z = 0.0f;
shootDirection = Camera.main.ScreenToWorldPoint (shootDirection);
shootDirection = shootDirection - transform.position;
Rigidbody2D bulletInstance = Instantiate(bulletPrefab, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
bulletInstance.velocity = new Vector2(shootDirection.x * speed, shootDirection.y * speed);
错误指向我在控制台中就是这一行:
bulletInstance.velocity = new Vector2(shootDirection.x * speed, shootDirection.y * speed);
如果有人可以指出我的错误或发生了什么,那将会非常有帮助。
答案 0 :(得分:1)
我认为问题在于你想说bulletInstance
是一个拥有Rigidbody2D的GameObject,而不是它是一个。
未经测试的代码:
GameObject bulletInstance = Instantiate(...) as GameObject;
Rigidbody2D rb2d = bulletInstance.getComponent<Rigidbody2D>();
rb2d.velocity = new Vector2(...);