1

I am making a game. In my game, a ball is going around and if it hits a trap, it will die, and you will have to restart. My problem is: I can't figure out a way to make a button appear on the current scene when you hit the trap. Im scripting in C#.

using UnityEngine;

public class PlayerCollision : MonoBehaviour{
public Rigidbody rb;

void OnCollisionEnter(Collision collisionInfo)
{
    if (collisionInfo.collider.name == "Trap_Spike")
    {

        FindObjectOfType<Gamemanager>().RestartGame();




    }
}

}

The trap has the tag Trap_Spike on it.

My RestartGame script looks like this:

using UnityEngine;

public class Gamemanager : MonoBehaviour{

public void RestartGame()
{


}

}

So I'll be open for any help I can get

Magnus
  • 91
  • 1
  • 2
  • 8

2 Answers2

2

Have a Button under your Canvas object. Deactivate the button in the hierarchy by unselecting this checkbox.

enter image description here

In your Gamemanager script have a field

Button ResetButton;

Attach the button to this field in your Unity Inspector.

To show the button, do this in RestartGame()

ResetButton.gameObject.SetActive(true);
Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42
1

To display a button you will want a Canvas with a button in it.

Right click in your hierarchy and select UI -> Button. This will create the neccesary objects: Canvas/Button & EventSystem. Leave EventSystem where it is, it's related to the Canvas but you don't need to care about it, just leave it there for now.

So by deafult you want to hide this canvas, and upon RestartGame you want to show it, right? So go ahead and disable it by ticking the checkbox in the inspector, then in your GameManager, you do something like:

public void RestartGame()
{
    FindObjectOfType<Canvas>().setActive(true);
}

You'll need to register what happens when you click the button as well. This script assumes that it's attached to the GameObject that has the UI Button on it:

void Start() {
    GetComponent<Button>().onClick.AddListener(RestartScene);
}

void RestartScene() {
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Fredrik Schön
  • 4,888
  • 1
  • 21
  • 32