Why is max health set to -5?

The Inspector takes any number you type.

Why is max health set to -5?

The problem

Nothing checks the Inspector.

public class Enemy : MonoBehaviour{    [SerializeField] int maxHealth = 100;    [SerializeField] float speed = 4f;    [SerializeField] Rigidbody rb;}

A stray minus, a reference nobody filled in: nothing complains until the game breaks.

The fix

Check it as it's typed.

OnValidate runs in the editor whenever a value changes in the Inspector, and when the script loads.

you type→OnValidate→fix it or warn

The fix in code

Clamp it, flag it.

void OnValidate(){    maxHealth = Mathf.Max( 1, maxHealth );    speed = Mathf.Max( 0f, speed );     if ( rb == null )        Debug.LogWarning( "No Rigidbody set", this );}

Bad numbers snap back as you type, and a missing reference gets a warning.

Watch out

It never runs in your build.

OnValidate is editor only, and it can run off the main thread. Keep it to simple checks.

Clamp a value
good
Warn about a reference
good
Spawning, game rules
never here

The rule

Check data where it's typed.

Runs
on every Inspector change
Use it to
clamp, warn
Never
game logic