[Solved] How To Call GameOver Script On Player Death

Hi there I have a simple question. I been having trouble calling this Game Over script

ing UnityEngine;

/// <summary>
/// Start or quit the game
/// </summary>
public class GameOverScript : MonoBehaviour
{
    private GUISkin skin;

   
    void Start()
    {
        // Load a skin for the buttons
        skin = Resources.Load("GUISkin") as GUISkin;
    }

    void OnGUI()
    {
        const int buttonWidth = 170;
        const int buttonHeight = 80;

        // Set the skin to use
        GUI.skin = skin;
       
        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("Game");

           
        }
       
        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
            ),
            "Exit"
            )
            )
        {

            // Reload the level
            Application.LoadLevel("TitleScreen");

           
        }
    }
  }

I attached this script to a empty game object and disable it so it does not show on load. Then I make another script below and add it to the player. So when player dies want to get the script above to show! But does not work! Get

"
NullReferenceException: Object reference not set to an instance of an object
CallGameOver.OnDestroy () (at Assets/UI Scripts/GameOver/CallGameOver.cs:11) "

using UnityEngine;
using System.Collections;

public class CallGameOver : MonoBehaviour
{


        void OnDestroy ()
        {

                transform.parent.gameObject.AddComponent<GameOverScript> ();

        }
}

I also tried below but did not seem to work and same error. Please advise thank you very much.

using UnityEngine;
using System.Collections;

public class CallGameOver : MonoBehaviour
{


        void OnDestroy ()
        {

               GameObject.Find("GameOver").active = true;

        }
}

You want to use a public variable for the gameObject with the script and drag that onto it in the editor in the player script:
public GameObject gameOverObject;

The in on destroy, you get the script from that object using GetComponent:
gameOverObject.GetComponent().enabled = true;

1 Like

Starting to notice you. I see that you are active in helping people and notice that you reply to many questions. A great help to the community. Thank you for your prompt and easy to understand answer and it worked great. :slight_smile:

Glad I could help.

1 Like