architecture
[Input System] Fix FindAction NullReferenceException and Reference Breakage
Solution
Unity 2020.3.x - Unity 6.3.x
Published Thu, Mar 26
A NullReferenceException is triggered within the Update loop when FindAction fails to return a valid instance. This common regression occurs after script refactoring or moving classes into a namespace, causing string-based lookups like GameObject.Find to fail silently or FindAction to mismatch with the updated Input Action Asset configuration.
Runtime crashes are mitigated by replacing fragile string-based lookups with Object.FindAnyObjectByType and validating that FindAction successfully binds to the active asset.
- Ensure the strings provided to FindAction exactly match the names defined in the active
Input Action Asseteditor. - Verify the
InputActionMapcontaining the actions is enabled viaEnable()before pollingIsPressed()in the logic loop. - Replace name-dependent lookups with
Object.FindAnyObjectByType<your game management class>()to maintain robust references regardless of hierarchy or namespace changes. - Implement null-conditional access or debug assertions in
Start()to verify FindAction has correctly bound to the expected input actions.
Additional Tips
- Use a generated C# class for your input asset to access actions via strongly-typed properties instead of using FindAction strings.
- Check the
PlayerInputcomponent on your player object to confirm the correct asset is assigned and initialized.
using UnityEngine;
using UnityEngine.InputSystem;
namespace GamesChallenge.FlorpyBorb
{
public class PlayerController : MonoBehaviour
{
private InputAction m_flapSpace;
private InputAction m_flapMouse;
private Rigidbody2D m_rigidbody;
private GameManager m_gameManager;
void Start()
{
// Ensure action names match the .inputactions asset exactly
m_flapSpace = InputSystem.actions.FindAction("Jump");
m_flapMouse = InputSystem.actions.FindAction("Flap");
m_rigidbody = GetComponent<Rigidbody2D>();
// Replace GameObject.Find with type-safe lookup
m_gameManager = Object.FindAnyObjectByType<GameManager>();
if (m_flapSpace == null) Debug.LogError("Jump action not found!");
}
void Update()
{
if (m_gameManager != null && m_gameManager.isGameRunning)
{
// Use null-conditional to prevent NRE if FindAction failed
bool inputDetected = (m_flapSpace?.IsPressed() ?? false) || (m_flapMouse?.IsPressed() ?? false);
if (inputDetected)
{
PerformFlap();
}
}
}
private void PerformFlap()
{
m_rigidbody.linearVelocity = Vector2.zero;
m_rigidbody.AddForce(Vector2.up * 5.0f, ForceMode2D.Impulse);
}
}
}
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
[Canvas System] Duplicated UI Assets: Awake Initialization Skip[Collision] Stop Multiple OnTriggerEnter Events Firing[gRPC Client] Prevent Setup Headaches in 6.3 Builds
Content inspired by a Unity discussion post.