I want to increase the value of extralives when player comes in contact with the health sprite. I have setup others details like box colllider and is triggered perfectly. I just want to know the command to increase a game object value (i.e. UIExtraLives increment by 1) . Each life is represented by an Health sprite and not the text . Bottom right down is the shown window for lives in the image. [100004-screenshot-20.png*|100004]
public GameObject[] UIExtraLives;
public void AddLife(int amount)
{
// update UI
int i = UIExtraLives.Length;
i++;
UIExtraLives.Length *.SetActive (true);*
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<PlayerScript>())
{
other.gameObject.GetComponent<PlayerScript>().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);
}
thanks for the reply. I want to know one more thing .
why u wrote
if (actualExtraLives < maximalExtraLives)
actualExtraLives += amount;
if (actualExtraLives > 0)
UIExtraLives[(actualExtraLives - 1)].SetActive (true);
Isn’t there in command where we can increase the value of UIExtraLives in just one line.
Like :
UIExtraLives[ (initial valual of UIExtraLives + 1)].SetActive(true);
Sorry for asking this but I just started coding a while back.