Not sure how to call a public void from another script

I’m currenlty working on a project and I’ve gotten stuck on a really simple thing, I’m trying to make it so that if the player picks up a certain item the player gets healed

(Player script)
public void Heal (int _healamount)

{
if (currentHealth >= 100)
return;

currentHealth += _healamount;

Debug.Log(transform.name + “now has” + currentHealth + “health”);

}

but I’m not sure how to call it from the items script
(item script)

void OnTriggerEnter (Collider info)
{
if (info.tag == “Player”)
{
//heal player
Destroy(gameObject);
}
}

}

Look at GetComponent and TryGetComponent(out T) which are your primary method of getting references to components on other game objects.

thanks, I changed the code to this:

public void OnTriggerEnter (Collider info)
{
if (info.tag == “Player”)
{
Player playerheal = GetComponent();
playerheal.Heal(10);
Destroy(gameObject);
}
}
}

but now when I move the player into the object it comes up with an error:
NullReferenceException: Object reference not set to an instance of an object
HealthUp.OnTriggerEnter (UnityEngine.Collider info) (at Assets/HealthUp.cs:14)

I’ve looked around but I’m not sure why, any ideas?

Then you should look at one of the pinned threads on this sub-forum which is all about null reference exceptions.

I’ve checked and I think the problem lies in the playerheal.Heal(10); but I have no idea whats causing it

try to point out difference between

Player playerheal = GetComponent<Player>();

and

Player playerheal = info.gameObject.GetComponent<Player>();

it will help u alots :wink:

ah lol, I only recently started using unity so thanks for your help!

Referencing variables, fields, methods (anything non-static) in other script instances:

REMEMBER: it isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.

ALSO, this always stands:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

I tried to use this to fix my own problem, but I got the error that “info” does not exist currently

Well does your script have a variable/member called info? Probably not. Because the example is contextual to OP’s code.

Rather than copy code off random posts (which is a terrible idea), and necro an old post, it’d be wiser to make your own thread detailing your problem.

3 Likes