-1

script 1

[SerializeField] public int staminaLeft;
[SerializeField] public int maxStamina;

void Start()
{
    maxStamina = 100;
    staminaLeft = maxStamina;
}

second script

public PlayerStamina playerStamina;
private void Update()
{
    if (playerStamina.staminaLeft <= 0)
    {
    }
    else if (playerStamina.maxStamina > 0 && !fillImage.enabled)
    {
    }
}

It says Object reference not set to an instance of that object but I am quite sure that playerStamina.staminaLeft has a value that isn't null

Mirazz_Boi
  • 13
  • 1
  • 3
  • It's more likely that `playerStamina` is `null` as you don't actually initialize it anywhere. – juharr Jul 23 '21 at 15:34
  • The error says otherwise ... and your code also. `playerStamina` is not initialized (at least not in the code you show) – derpirscher Jul 23 '21 at 15:36
  • I took your advice and tried to initialize it with the new command by changing it to | new public int | instead but that doesn't fix that problem. Do you know what should I do? – Mirazz_Boi Jul 23 '21 at 16:06
  • @Mirazz_Boi: What is "new public int"? It sounds like you might want to take a look at some introductory C# tutorials and walk through some basic syntax. Creating/initializing an object (with the `new` keyword) is generally covered by such tutorials. I suppose it's also possible that you may be relying on a framework to initialize object/properties somewhere, but we wouldn't know that. (Also, an `int` *can't* be `null`, so you seem to be looking in the wrong place to begin with.) – David Jul 23 '21 at 16:11
  • @Mirazz_Boi Is PlayerStamina another component attached to the same object as the second script in the Unity editor? If so, you need to get that component in the Awake function in the second script. Something like this in your Awake function: playerStamina = GetComponent(); – MoreFoam Jul 23 '21 at 16:13

1 Answers1

0

It says that your object variable playerStamina is null.

I don't see in your code that you checked that this object is not null so that it might be that this object is null.

You might initialize it with the new keyword and also you might verify in your method that playerStamina is not null to avoid unhandled exceptions.

Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116