Restarting the scene when button is pressed
Im currently trying to make it so a GUI button, when clicked/pressed, resets the scene. but i cant seem to get it to trigger the code im trying to get it load. could somebody help me?
using UnityEngine;
using System.Collections;
public class Reset : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void TaskOnClick() {
Application.LoadLevel(Application.loadedLevel);
}
}
Answer by UnityCoach · Jan 19, 2017 at 02:23 PM
If you're using a Unity.UI.Button
, make your TaskOnClick
method public, then assign an event to the Button that calls that method.
Answer by steo · Jan 19, 2017 at 04:59 PM
I recommend you subscribe to onClick from code (not from Inspector):
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
[RequireComponent(typeof(Button))]
public class Reset : MonoBehaviour {
private Button button;
void Start() {
button = GetComponent<Button>();
button.onClick.AddListener(TaskOnClick);
}
void TaskOnClick() {
Application.LoadLevel(Application.loadedLevel);
}
}
Note that this script needs component Button on the same gameObject.
Line [RequireComponent(typeof(Button))]
guaranties that when you add this component to gameObject, Unity also adds Button to it. But it does'n if component Reset is already on gameObject when you add this attribute.
Your answer
Follow this Question
Related Questions
How to do Unlockable Items for a Character Collection Clicker Game? How to disable buttons? 0 Answers
Detect if UI button clicked 1 Answer
Make button to be pressed by code ? 2 Answers
Button.onClick running too many times 0 Answers
GVR reticle do not hover on buttons, and the click only work outside of button shape 0 Answers