First: Your player GameObject and your health sprite GameObject must both have a collider 2D. The Health Collider2D must be set as Trigger.
Then in your health object, Add a script with these lines of codes:
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.GetComponent())
{
other.gameObject.GetComponent().AddLife(1);
//If you want to destroy the object...
Destroy(gameObject);
}
}
And of course, change the PlayerScript to the proper name of the script containing the public void AddLife(int amount).
Then you should change your codes in AddLife(int amount):
public GameObject[] UIExtraLives;
public int actualExtraLives = 1, maximalExtraLives = 5;
public void AddLife(int amount)
{
if (actualExtraLives < maximalExtraLives)
actualExtraLives += amount;
if (actualExtraLives > 0)
UIExtraLives[(actualExtraLives - 1)].SetActive (true);
}
↧