Home > Software design >  How do you restart a void Start after an IF statement
How do you restart a void Start after an IF statement

Time:08-07

I am coding myself a 2D little RPG game with very little experience in coding. I finished my Turn-Based Combat but now I need to add an automatic restart after losing.

I figured it could easily be done by making void Start() start again and reset values I need but I sadly couldn't find any way to do it.

        if (enemyHealth <= 0)
    {
        wonlostPanel.SetActive(true);
        wonlostDisplay.GetComponent<TextMeshProUGUI>().text = "You WON!";
        StopAllCoroutines();
    }
    else if (playerHealth < 0) 
    {
        wonlostPanel.SetActive(true);
        wonlostDisplay.GetComponent<TextMeshProUGUI>().text = "You Lost!";
        StopAllCoroutines();
        
    }
}
private void Start()
{
    enemyHealth = 100;
    playerHealth = 100;
    enemyState = "Preparing For Attack";
    playerDamage = 50;
    healPotions = 10;

}

CodePudding user response:

It is a bad practice to call Start() method from any other method in the script even though you declared it as public, it's a default method called by Unity at the start of the game. What you can do is move all your code that's resetting the values into a new method and call it in both Start() method and when the player's health goes below 0.

private void Start() => ResetValues();

private void ResetValues()
{
    enemyHealth = 100;
    playerHealth = 100;
    enemyState = "Preparing For Attack";
    playerDamage = 50;
    healPotions = 10;
}
else if (playerHealth < 0) 
{
    wonlostPanel.SetActive(true);
    wonlostDisplay.GetComponent<TextMeshProUGUI>().text = "You Lost!";
    StopAllCoroutines();

    ResetValues();
}
  • Related