首页 > 解决方案 > 从类调用函数时抛出 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;
    }

感谢您的时间。如果您需要更多信息,请评论您需要什么。

标签: c#unity3d

解决方案


推荐阅读