Can I make a script not use initialization values?

I’m sorry if the title is weird, I am not sure how to phrase this problem but I will try my best.
I have a state machine and in my state factory I create all the different states for the player. And to try to keep all the variables for each state local to that state, I have each state initializing its own values. However, I also want to be able to tweak them in the inspector. This is where the problem is. Because I initialize the states in the state factory, all the variables are reset to their initialization values once I start the game and the values I had set in the inspector are overwritten. So my question is if there is any way around this? Or do I have to rethink how I organize the variables?

[CreateAssetMenu(fileName = "State Factory", menuName = "Scriptable Objects/State Factory")]
public class PlayerStateFactory : ScriptableObject
{
    private PlayerStateMachine context;
    [SerializeField] private PlayerGroundedState groundedState;
    [SerializeField] private PlayerJumpState jumpState;
    [SerializeField] private PlayerSlideState slideState;

    public void Initialize(PlayerStateMachine currentContext)
    {
        context = currentContext;

        groundedState = new PlayerGroundedState(context, this);
        jumpState = new PlayerJumpState(context, this);
        slideState = new PlayerSlideState(context, this);
    }

    public PlayerState Grounded() { return groundedState; }

    public PlayerState Jump() { return jumpState; }

    public PlayerState Slide() { return slideState; }
}
[System.Serializable]
public class PlayerJumpState : PlayerState
{
    [SerializeField] private float jumpHeight = 2f;
    [SerializeField] [Range(0.5f, 3f)] private float fallMultiplier = 1.5f;
    [SerializeField] [Range(0f, 0.5f)] private float coyoteThreshold = 0.2f;

Check that existing fields are null before assigning a value to them.

All the cool kids are using the Null Coalescing Assignment Operator these days:

groundedState ??= new PlayerGroundedState(context, this);

(Requires C# 8.0)

1 Like