- Home /
Need to increase the gameobject value .
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.
public GameObject[] UIExtraLives;
public void AddLife(int amount)
{
// update UI
int i = UIExtraLives.Length;
i++;
UIExtraLives.Length [i].SetActive (true);
}
Answer by M-G-Production · Aug 16, 2017 at 05:44 PM
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);
}
Answer by dhruv777 · Aug 17, 2017 at 10:13 AM
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.
First, I guessed that there must be a limit to your extra lives, so I created a top limit (maximalExtraLives)
And yes, of course you can add a value to your array! But it doesn't seems like what you want to do, because it looks like you dragged and dropped some GameObjects in your array... Is the Lenght of the array already defined? If so the maximal limit represent the 'Lenght' so it won't throw an error!
But the code you are looking for is:
UIExtraLives[(UIExtraLives.Lenght+1)];
Your answer
Follow this Question
Related Questions
How can I add the OnTriggerEnter function to all game objects that I instantiate? 1 Answer
Why are these object passing through each other? 1 Answer
Calculating Scrolling GameObject x position scrolling pass another GameObject x postion (2D Game) 1 Answer
How to fix a Missing Refrence Exception Error 1 Answer
Update list on mouse click 1 Answer