Background
In previous post we saw how to setup unity for creating Android application. In this post we will see how to create a simple GUI button in a scene and put in in the center of your screen.
How to center a GUI button in Unity
Create or load an existing project. Next create a C# script and attach it to any of the objects on the screens. You can attach it to the camera as well. I am doing the same for this post. Now open this script in Monodevelop.
I have three different scenes in my project -
- GameStart
- GamePlay
- GameEnd
So create a C# script called GameStart.cs (you can name it anything you want)., attach it to camera in GameStart scene and open it in Monodevelop of editing.
Paste following code in it -
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameStart : MonoBehaviour { public void OnGUI(){ if(GUI.Button(new Rect(Screen.width/2-50,Screen.height/2-25,100,50),"Start Game!")) { Debug.Log("Start Button clicked"); Application.LoadLevel ("GamePlay"); } } }
Now lets understand whats going on. OnGUI() is the method that is called by Unity engine to render GUI components. We are going to add our button in this method.
Next we create a button using method GUI.Button() which takes its x position, y position, it's width and it's height as Rect object which is 1st argument to Button. 2nd argument is the text itself that will be shown on the button UI. We are showing "Start Game" there. What goes inside the wrapped if will get executed when the button is clicked. We are simply logging the click event and loading scene2 i.e GamePlay scene.
Point to note here is the x,y coordinates and the height/width of the Button. Notice how we have used Screen.width and Screen.height values here, then divided it by 2 to get mid and then adjusted the coordinates as per the actual width and height of the button we want.
It would look like below -
Now start up console. You can do so using
- Windows -> Console
It will also load scene 2 but ignore that for now. Monodevelop code looks like below -
No comments:
Post a Comment