An error occurred while creating Slider Health and shield

// Look for an object with tag hp_Player and take the Slider component from it
_slider_hp_Player = GameObject.FindGameObjectWithTag("sl_HP").GetComponent<Slider>();
// Look for an object with tag hp_Shield and take the Slider component from it
_slider_hp_Shield = GameObject.FindGameObjectWithTag("sl_Shield").GetComponent<Slider>();

I’d say it is a terrible tutorial but it is what it is.
Since you didn’t get a null reference in Awake I can assume that GameObject.FindGameObjectWithTag() probably did find a game object matching with that tag.
However, GetComponent<Slider>() probably returns null because there is no Slider component on that game object.

Since you’re a beginner, I’d suggest changing the 2 variables from private to public.

// Reference private to the UI's health bar.
    private Slider _slider_hp_Player;
    // Reference private to the UI's shield bar.
    private Slider _slider_hp_Shield;

Then drag drop a reference from the scene into the components fields in the inspector.
Then remove the 2 lines that find a game object & get component.
You also might want to change the name of the variable because it is then no longer private.
public fields are usually PascalCase.
private fields either with a _ prefix or just lowercase. (which sometimes differs from dev to dev)

The first rule of GameObject.Find and relatives is to not use it at all.

Instead of attaching the script to the thread post, use code tags instead

1 Like