c# - 从类调用函数时抛出 NullObjectReference
问题描述
我正在开发一个 Unity2D 游戏,其类用作枪支系统的模板(我知道这不是术语)。游戏开始时,会调用一个函数以在 UI.Image 元素中显示枪的缩略图。但是当我去 Unity 开始游戏时,它给了我编译器编辑器NullReferenceException: Object reference not set to an instance of an object PlayerScript.Start () (at Assets/Scripts/PlayerScript.cs:19)
。这是 PlayerScript.cs 的相关部分:
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
[SerializeField] static KeyCode fireKey;
[SerializeField] static GameObject gunGameObject;
[SerializeField] static GunObject currentGun;
[SerializeField] static GunObject starterGun;
private float movementSpeed = 5f;
// Start is called before the first frame update
void Start() {
currentGun = starterGun;
Debug.Log("currentGun is " + currentGun);
currentGun.switchGun();
}
这是调用 switchGun() (GunObject.cs) 的模板文件
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Gun")]
public class GunObject : ScriptableObject {
[SerializeField] string gunName;
[SerializeField] public Sprite uiImage;
[SerializeField] GunObject nextUpgrade;
[SerializeField] int damage;
[SerializeField] int shotsPerSecond;
[SerializeField] int ammoCapacity;
[SerializeField] float bulletSpeed;
public void switchGun() {
Game game = new Game();
game.gunDisplay.sprite = uiImage;
}
感谢您的时间。如果您需要更多信息,请评论您需要什么。
解决方案
推荐阅读
- powershell - 我应该怎么做才能正确安装cordova?
- android - ConstraintLayout - Ellipsize 开始不起作用
- python - matplotlib 不绘制最后一个数据点
- swift - didReceiveRemoteNotification 和 iOS 14 崩溃
- types - Rust 中 itertools::process_results() 的回调类型签名应该是什么?
- formik - 是的,使用一个字段进行验证,但有两个可能的选项 (OR)
- r - 尝试将变量制成表格时,如何阻止出现的观察次数?
- swift - 我怎么知道加速度计何时静止?我在 Swift 中通过蓝牙使用外部加速度计
- android - 如何在 Materialtextinput Android 中结束可绘制后添加文本
- android - Kotlin 是如何知道 applicationContext 来自 getApplicationContext() 的?