Search Unity

Question null reference exception

Discussion in 'Scripting' started by CloudLne, Jan 10, 2024.

  1. CloudLne

    CloudLne

    Joined:
    Jan 2, 2024
    Posts:
    3
    Hi I am new to unity game development and I am trying to run locomotion movement on my character. I found a script online fixed all the animations and controllers but i get this message


    NullReferenceException: Object reference not set to an instance of an object
    Character.Update () (at Assets/Locomotion/Scripts/Character.cs:73)

    The full script is as follows


    using UnityEngine;
    using UnityEngine.InputSystem;

    public class Character : MonoBehaviour

    {
    [Header("Controls")]
    public float playerSpeed = 5.0f;
    public float crouchSpeed = 2.0f;
    public float sprintSpeed = 7.0f;
    public float jumpHeight = 0.8f;
    public float gravityMultiplier = 2;
    public float rotationSpeed = 5f;
    public float crouchColliderHeight = 1.35f;

    [Header("Animation Smoothing")]
    [Range(0, 1)]
    public float speedDampTime = 0.1f;
    [Range(0, 1)]
    public float velocityDampTime = 0.9f;
    [Range(0, 1)]
    public float rotationDampTime = 0.2f;
    [Range(0, 1)]
    public float airControl = 0.5f;

    public StateMachine movementSM;
    public StandingState standing;
    public JumpingState jumping;
    public CrouchingState crouching;
    public LandingState landing;
    public SprintState sprinting;
    public SprintJumpState sprintjumping;

    [HideInInspector]
    public float gravityValue = -9.81f;
    [HideInInspector]
    public float normalColliderHeight;
    [HideInInspector]
    public CharacterController controller;
    [HideInInspector]
    public PlayerInput playerInput;
    [HideInInspector]
    public Transform cameraTransform;
    [HideInInspector]
    public Animator animator;
    [HideInInspector]
    public Vector3 playerVelocity;


    private void Start()
    {
    controller = GetComponent<CharacterController>();
    animator = GetComponent<Animator>();
    playerInput = GetComponent<PlayerInput>();
    cameraTransform = Camera.main.transform;

    movementSM = new StateMachine();
    standing = new StandingState(this, movementSM);
    jumping = new JumpingState(this, movementSM);
    crouching = new CrouchingState(this, movementSM);
    landing = new LandingState(this, movementSM);
    sprinting = new SprintState(this, movementSM);
    sprintjumping = new SprintJumpState(this, movementSM);

    movementSM.Initialize(standing);

    normalColliderHeight = controller.height;
    gravityValue *= gravityMultiplier;
    }

    private void Update()
    {
    movementSM.currentState.HandleInput();

    movementSM.currentState.LogicUpdate();
    }

    private void FixedUpdate()
    {
    movementSM.currentState.PhysicsUpdate();
    }
    }


    It occurs twice both on line 73 and line 80 which are

    movementSM.currentState.HandleInput();
    movementSM.currentState.PhysicsUpdate();

    respectively

    I dont really know why it does it does anyone have an idea? Or would anyone be willing to offer a fix for this issue
     
  2. arkano22

    arkano22

    Joined:
    Sep 20, 2012
    Posts:
    1,924
    Most likely, movementSM.currentState is null. Without any info on how the StateMachine class is implemented, there's no way to tell why.
     
  3. CloudLne

    CloudLne

    Joined:
    Jan 2, 2024
    Posts:
    3
    ill send both the state machine and state code here

    state code


    using UnityEngine;
    using UnityEngine.InputSystem;

    public class State
    {
    public Character character;
    public StateMachine stateMachine;

    protected Vector3 gravityVelocity;
    protected Vector3 velocity;
    protected Vector2 input;

    public InputAction moveAction;
    public InputAction lookAction;
    public InputAction jumpAction;
    public InputAction crouchAction;
    public InputAction sprintAction;

    public State(Character _character, StateMachine _stateMachine)
    {
    character = _character;
    stateMachine = _stateMachine;

    moveAction = character.playerInput.actions["Move"];
    lookAction = character.playerInput.actions["Look"];
    jumpAction = character.playerInput.actions["Jump"];
    crouchAction = character.playerInput.actions["Crouch"];
    sprintAction = character.playerInput.actions["Sprint"];

    }

    public virtual void Enter()
    {
    Debug.Log("enter state: "+this.ToString());
    }

    public virtual void HandleInput()
    {
    }

    public virtual void LogicUpdate()
    {
    }

    public virtual void PhysicsUpdate()
    {
    }

    public virtual void Exit()
    {
    }
    }

    state machine code


    public class StateMachine
    {
    public State currentState;

    public void Initialize(State startingState)
    {
    currentState = startingState;
    startingState.Enter();
    }

    public void ChangeState(State newState)
    {
    currentState.Exit();

    currentState = newState;
    newState.Enter();
    }


    }

    these are the 3 codes that im using right now
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,826
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,676
    You don't need to send or post anything for this error.

    The answer is always the same... ALWAYS!

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that


    ALSO: just note that you might want to find a better tutorial source. This script is written to fail constantly because it embodies at least half a dozen hard assumptions and does nothing to check or report them, such as this cluster of code:

    Code (csharp):
    1. controller = GetComponent<CharacterController>();
    2. animator = GetComponent<Animator>();
    3. playerInput = GetComponent<PlayerInput>();
    4. cameraTransform = Camera.main.transform;
    In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.

    If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way(tm) success of accessing things in your game.


    "Stop playing 'Where's GameWaldo' and drag it in already!"





    Keep in mind that using GetComponent<T>() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.

    Here's the bare minimum of stuff you absolutely MUST keep track of if you insist on using these crazy Ninja methods:

    - what you're looking for:
    --> one particular thing?
    --> many things?
    - where it might be located (what GameObject?)
    - where the Get/Find command will look:
    --> on one GameObject? Which one? Do you have a reference to it?
    --> on every GameObject?
    --> on a subset of GameObjects?
    - what criteria must be met for something to be found (enabled, named, etc.)

    If you are missing knowledge about even ONE of the things above, your call is likely to FAIL.

    This sort of coding is to be avoided at all costs unless you know exactly what you are doing.

    Botched attempts at using Get- and Find- are responsible for more crashes than useful code, IMNSHO.

    If you run into an issue with any of these calls, start with the documentation to understand why.

    There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.

    In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.

    It is ALWAYS better to go The Unity Way(tm) and make dedicated public fields and drag in the references you want.




    This guy has a lot of great tutorials:

    Imphenzia: How Did I Learn To Make Games: