Hey Unity Community i need some help wondering why my script is calling before the player dies. I have a gameover script that calls after the player loses all their lives and for some reason its called before the player dies. Here is the script for reference
Game Manager script
public class GameController : MonoBehaviour
public Gameover GameOverScript;
public int playerLives = 2;
public GameObject player;
public Texture shipTexture;
void Update()
{
if (player == null && playerLives >= 1) {
playerLives--;
player = ((Transform)Instantiate (playerShip, new Vector3 (0, 0, 0), playerShip.transform.rotation)).gameObject;
}
}
void OnGUI()
{
if (playerLives != 0)
{
for (int i=1; i<=playerLives; i++)
{
GUI.DrawTexture (new Rect (i * 36, 0, 750, 48), shipTexture, ScaleMode.ScaleToFit, true);
}
}
if (playerLives == 0 && player == null)
{
GameOver();
}
}
void GameOver()
{
GameOverScript = GameObject.FindGameObjectWithTag ("GameOver").GetComponent<Gameover>();
}
Game Over script
void OnGUI()
{
const int buttonWidth = 120;
const int buttonHeight = 60;
if (
GUI.Button(
// Center in X, 1/3 of the height in Y
new Rect(
Screen.width / 2 - (buttonWidth / 2),
(1 * Screen.height / 3) - (buttonHeight / 2),
buttonWidth,
buttonHeight
),
"Retry!"
)
)
{
// Reload the level
Application.LoadLevel("Stage1");
}
if (
GUI.Button(
// Center in X, 2/3 of the height in Y
new Rect(
Screen.width / 2 - (buttonWidth / 2),
(2 * Screen.height / 3) - (buttonHeight / 2),
buttonWidth,
buttonHeight
),
"Back to menu"
)
)
{
// Reload the level
Application.LoadLevel("Menu");
}
}
I have the Gameover script attached to an empty game object is thats why its called earlier? Here is a pic of how it looks like. If you can help with this thank you!
In Update(), you have: if (player == null && playerLives >= 1) { playerLives--; ... } So on every frame you reduce the player's lives until it hits 0, at which point GameIver() is called.
– tanoshimiHave you tried to disable the Gameover script in the Awake() function on the Gameover script, then try to enable it in your Gameover function of your Game manager script? Something like: void GameOver() { GameOverScript = GameObject.FindGameObjectWithTag("GameOver").GetComponent<Gameover>(); GameOverScript.SetEnabled(True); } I'm not 100% sure on this, but I don't know if you need the GameObject.FindGameObjectWithTag... line because you declared it public and will be setting it in the editor. I could be wrong though.
– DocMcShot