Hello, I want to make a lives counter (max lives =3), that decrease when the character hits to obstacles and increase when hits the heartpotion.
I already write an switch case in update method and it worked, but I am concerned about the performance. It feels wrong as the update method work on every frame but change in lives counter is not so often.
How can I do it in a better and optimized way?
Note: Sorry if this is a super-simple and noob question but I am new in coding and trying to figure out things by myself. I would be grateful for any help. Thank you!
this script attached to UI:
private void Update()
{
//gameObject.transform.GetChild();
//reach to the child
switch (TotalScores.lives)
{
case 3:
gameObject.transform.GetChild(2).gameObject.SetActive(true);
gameObject.transform.GetChild(1).gameObject.SetActive(true);
Debug.Log("can sayısı" + TotalScores.lives);
break;
case 2:
Debug.Log("can sayısı" + TotalScores.lives);
gameObject.transform.GetChild(2).gameObject.SetActive(false);
gameObject.transform.GetChild(1).gameObject.SetActive(true);
break;
case 1:
Debug.Log("can sayısı" + TotalScores.lives);
gameObject.transform.GetChild(2).gameObject.SetActive(false);
gameObject.transform.GetChild(1).gameObject.SetActive(false);
break;
case 0:
Debug.Log("can sayısı" + TotalScores.lives);
//gameover
break;
default:
Debug.Log("can sayısı" + TotalScores.lives);
break;
}
}
and this script attached to the character:
private void OnTriggerEnter2D(Collider2D other)
{
if ((other.gameObject.CompareTag("Obstacle")) && (!coroutineRunning)) //corutinede değilse ve engele çarparsa
{
if (TotalScores.lives < 3 || TotalScores.lives > 0)
{
TotalScores.lives--;
StartCoroutine(WaitDamage());
}
}
else if (other.gameObject.CompareTag("Scoring"))
{
//FindObjectOfType<Scoring>().IncreaseScore();
TotalScores.totalScore++;
_textscore.text = "Score " + TotalScores.totalScore.ToString();
}
else if (other.gameObject.CompareTag("Artican"))
{
if (TotalScores.lives < 3 || TotalScores.lives >= 0)
{
TotalScores.lives++;
}
Destroy(other.gameObject);
//FindObjectOfType<Scoring>().Healthgain();
}
else if (other.gameObject.CompareTag("Zemin"))
{
transform.position = Vector3.zero;
//FindObjectOfType<Scoring>().Zemintouch();
StartCoroutine(WaitDamage());
}
else if (other.gameObject.CompareTag("Sise"))
{
Destroy(other.gameObject);
//TotalScores.totalScore+= 100
}
}