- Home /
Loading scene with a prefab GUI button?
I have looked everywhere on the internet and can't seem to find an answer for this. Maybe my solution is so simple that no one has ever bothered to ask the question.
I am using a prefab UI asset package I bought from the Asset Store (Holo UI, if it helps to know). So far I'm having no problems using it, other than that I cannot seem to figure out how to load a new scene when I click one of these prefab buttons.
I've emailed the asset creator for help, and he seemed confused that I was asking, pointing me to this tutorial on UI Events and Event Triggers. Fine. But this video and all the others I looked at never talk about prefab buttons, only using scripting to draw buttons:
private void OnGUI( ) {
if (GUI.Button(new Rect(x, y, w, h), "Load Level")) {
Application.LoadLevel ("Level");
}
}
I get it, but I don't want to draw a new Rect. I want to use the prefab button I dropped on my canvas in Unity. I also tried messing with Event Triggers as the video above suggested, but I can't seem to get an OnClick ( ) -> LoadLevel( ) link going.
Can someone please help with step-by-step directions from adding the prefab GUI button to loading the scene? I'm at my wit's end here. Thank you very much.
Answer by $$anonymous$$ · May 04, 2015 at 11:26 PM
Add your button
Create a new C# script and call it "ButtonHandler" and paste this code inside
using UnityEngine; using System.Collections;
public class ButtonHandler : MonoBehaviour { public void LoadScene(string sceneName) { Application.LoadLevel(sceneName); } }
Click on your button in the heirarchy and add the ButtonHandler script to your button
In the inspector find this part:
Click the plus icon under On Click() (the red box in the photo above)
Drag the button object from the heirarchy into the box that says "None (Object)" (red arrow below)
Click on the "No Function" dropdown and under "ButtonHandler" click on "LoadScene(string)" (red box above)
In the box below the drop down enter the name of your scene, for instance "Scene2"
Finally go to File > Build Settings and in the "Scenes in Build" section add both the scene with the button and the scene you want to change to. You can do this by opening each scene and clicking "Add Current" under the list of scenes.
I hope this helped. Feel free to ask any further questions if you need clarification
Your answer
Follow this Question
Related Questions
On Click paramaters disappear from button prefab? 5 Answers
Change to scene based on current scene 1 Answer
Play sound on button click before loading level. 3 Answers
GUI button inconsistent -1 Answers
GUI Creates a prefab? 1 Answer