1

i am making a game with c# in unity and i want that if you die in level 4 that you go back to level 0 but if you are in level 5 that you respawn in level 5 the code:

   {
        int currentSceenIndex = SceneManager.GetActiveScene().buildIndex;
        if (currentSceenIndex <= 4)
        {
            SceneManager.LoadScene(0);
        }
        else if (currentSceenIndex == 4)
        {
            SceneManager.LoadScene(4);
        }   
    }

what did i do wrong the respawn still works but i am always going back to level 0 how to fix this. I tried to follow an tutorial but it still did not work. I can't see the mistake and also I don't get any errors when playing the game so I don't know where the error is at.

kajvans
  • 85
  • 6
  • Ah - "but if you are in level 5 that you respawn in level 5 the code:" - how doe that translate into SceneManager.LoadScene(4); - particualrly given that level 4 seems to be if (currentSceenIndex <= 4), i.e. it is not 0 based? It likely is, but then your first condition is off by one. – TomTom May 18 '20 at 09:22
  • Did you try to use `if (currentSceenIndex < 4)` instead of `<=` ? – derHugo May 18 '20 at 09:26
  • if (currentSceenIndex < 4) that is the solution thanks – kajvans May 18 '20 at 09:29

2 Answers2

2

It sounds like you would rather want to use

if (currentSceenIndex < 4) 

instead of <= since currently the second block would never be reached since for currentSceenIndex == 4 it already executes the if block

var currentSceenIndex = SceneManager.GetActiveScene().buildIndex;
if (currentSceenIndex < 4)
{
    SceneManager.LoadScene(0);
}
else if (currentSceenIndex == 4)
{
    SceneManager.LoadScene(4);
}   
derHugo
  • 83,094
  • 9
  • 75
  • 115
0
public const int MinimumRespawnSceneIndex = 4;

public void Respawn()
{
    int currentSceenIndex = SceneManager.GetActiveScene().buildIndex;

    int spawnAtSceneIndex = currentSceenIndex < MinimumRespawnSceneIndex ? 0 : currentSceenIndex;

    SceneManager.LoadScene(spawnAtSceneIndex);
}
ChoopTwisk
  • 1,296
  • 7
  • 13
  • I like the use of the ternary operator but it would be preferable to pass the `MinimumRespawnSceneIndex ` as a value to the `Respawn(int MinimumRespawnSceneIndex)` method – akaBase May 18 '20 at 10:40