How can i access a value from another script that is attached to the same gameObject?

Hello everyone, I have two c# scripts attached to my Player game object, a HealthScript and a HealthBar Script. I’m trying to get the players ‘Hp’ value so that i can pass it into the Healthbar script to display the proper amount of health.

I’ve looked into using GetComponent to do this, but i’m pretty sure i’m using it incorrectly. What i tried doing in the Healthbar Script was this:

Hp = gameObject.GetComponent<HealthScript>();

This passes an error of:

The name ‘Hp’ does not exist in the
current context

This makes me think that i’m doing it entirely wrong.

If anyone could give me advice on what i should try next, i would really appreciate it. Thanks.

Where do you declare Hp? If this is a local reference or an occasional reference you can do:

  HealthScript Hp = gameObject.GetComponent<HealthScript>();

If you are going to need it frequently, declare Hp as a class instance variable at the top of the file:

private HealthScript Hp;

Then in start execute the line you list in your question.