【发布时间】:2021-03-02 18:18:48
【问题描述】:
我不知何故在 Unity 中得到了一个空引用异常。我为我的武器类创建了一个构造函数,并创建了另一个武器类(继承自 monobehaviour),它在其中创建具有统计数据的武器。在pistol.Stats(10, 0.5f, 2, 5, new Vector2(0.2f, 0.09f)); 中发生了一个空引用。
脚本 1:
public class WeaponClass
{
public float damage, spread, bulletsPerSec, rotationSpeed;
public string name;
public Vector2 shootPoint;
private Image image;
public WeaponClass Stats(float Adamage, float Aspread, float AbulletsPerSec, float ArotationSpeed, Vector2 Ashootpoint)
{
damage = Adamage;
spread = Aspread;
bulletsPerSec = AbulletsPerSec;
rotationSpeed = ArotationSpeed;
shootPoint = Ashootpoint;
return this;
}
}
脚本 2:
public class Weapons : MonoBehaviour
{
private PlayerControlls _playerControlls;
private WeaponClass pistol, m4 = new WeaponClass();
private Bullet _bullet;
public WeaponClass currentWeapon;
private GameObject bullet;
public Rigidbody2D bulletRb;
private float randomdirection;
public float randomdirectionangle;
void Start()
{
pistol.Stats(10, 0.5f, 2, 5, new Vector2(0.2f, 0.09f));
currentWeapon = pistol;
Debug.Log(currentWeapon);
}
void Update()
{
}
public void Shoot()
{
randomdirection = Random.Range(-currentWeapon.spread, currentWeapon.spread);
randomdirectionangle = Mathf.Atan2(randomdirection, currentWeapon.shootPoint.x) * Mathf.Rad2Deg;
Quaternion bulletrotation = new Quaternion(0, 0, randomdirectionangle, 0);
GameObject bulletclone = Instantiate(bullet, currentWeapon.shootPoint, _playerControlls.GunEquipped.transform.rotation);
bulletRb = bulletclone.GetComponent<Rigidbody2D>();
}
}
【问题讨论】:
-
你只是构造/实例化了
m4