[C#] Owner returning null value even though I defined it

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tobaz

I’m currently making a state machine for the player in my game. Every state inherits from a base player-state node
But when I run my game, I get an error in the debugger coming from the physics process in my Idle state.

Code for base player-state:

using Godot;
using System;
public class PlayerState : State
{
   public Player player;

   public override async void _Ready()
   {
    await ToSignal(Owner, "ready");
    player = Owner as Player;
    

   }
}

(Indentation might seem wrong on example but it’s right in the script)

Code for the Idle State:

    public class Idle_State : PlayerState
{
    public override void enter()
    {

    }

    public override void physics_update(float delta)
    {
        player.Character.anim_tree.Set("parameters/ground_blend/blend_amount", Mathf.Lerp((float)player.Character.anim_tree.Get("parameters/ground_blend/blend_ammount"), -1, delta * player.acceleration));
        player.speed = 0;

        player.Velocity.x = Mathf.Lerp(player.Velocity.x, player.Direction.x * player.speed, delta * player.acceleration);
        player.Velocity.z = Mathf.Lerp(player.Velocity.z, player.Direction.z * player.speed, delta * player.acceleration);
        player.air_velocity = 0;

        player.apply_gravity(delta);
        player.handle_input(delta);

        player.MoveAndSlide(player.Velocity + Vector3.Down * player.air_velocity, Vector3.Up);

        if (player.Direction.x != 0 || player.Direction.z != 0 && !player.sprint)
        {
            State_Machine.Transition_to("Walk");
        }
        else if (player.sprint)
        {
            State_Machine.Transition_to("Running");
        }
    }

}

“System.NullReferenceException: Object reference not set to an instance of an object”

Even though I defined my player in the player state class. I would appreciate any help to solve this problem.

Maybe your player isn’t assign since your ready function is call asynchronously. Why don’t you define player in your State_Machine class since it seem to be static ?

zeludtnecniv | 2023-01-31 12:26

:bust_in_silhouette: Reply From: auxterlibre

That was happening to me and the issue was an error in the owner class (Player in your case). But I just found out because I opened the class and Godot pointed out an error in the script. (I am using GDScript btw)