I have an issue where I get a NullReferenceException from an input action, but only on a blender 3d object; it doesn’t occur on the unity built-in object.
If I attach the GunController script onto a unity built-in object the script works perfectly fine, but it doesn’t work for a blender object. I get the reference to the fire InputAction from a central GameManger just btw.
Here’s the code so you don’t have to download files
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class GameManager : MonoBehaviour
{
static GameManager instance;
// Input Stuff
public static AIMInput aimInput;
public static InputAction look;
public static InputAction fire;
public static InputAction jump;
public static InputAction move;
private void Awake()
{
aimInput = new AIMInput();
look = aimInput.Player.Look;
fire = aimInput.Player.Fire;
jump = aimInput.Player.Jump;
move = aimInput.Player.Move;
}
// Start is called before the first frame update
void Start()
{
if (instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class GunController : MonoBehaviour
{
[SerializeField] Transform mainCam;
[SerializeField] LayerMask targetLayerMask;
// Input Stuff
InputAction fire;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (fire.WasPressedThisFrame()) FireRaycastShot();
}
void FireRaycastShot()
{
Ray ray = new Ray(mainCam.position, mainCam.forward);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, targetLayerMask.value))
{
Debug.Log("ray hit target");
Destroy(hitInfo.transform.gameObject);
}
}
public void OnEnable()
{
fire = GameManager.fire;
fire.Enable();
}
private void OnDisable()
{
fire.Disable();
}
}
This might be a race condition. Generally Awake and OnEnable get called together on all game objects, then Start gets called on all game objects. So I’m wagering the non-determinism is causing GunController to initialise first.
You can easily confirm this with some Debug.Logs.
If this is the case, the solution would be to initialise fire in Start instead. As a rule of thumb, any initialisation that depends on other game objects being ready should be done in Start.