I am working on a Unity2D game with a class that is used as a template (I know that's not the term) for a gun system. When the game starts, a function is called to show the gun's thumbnail in a UI.Image element. But when I go to Unity to start the game, it gives me the compiler editor NullReferenceException: Object reference not set to an instance of an object PlayerScript.Start () (at Assets/Scripts/PlayerScript.cs:19)
. Here is the relevant portion of 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();
}
Here is the template file from which it is calling 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;
}
Thank you for your time. If you need any more information, please comment what you need.