Need a script for Main Menu buttons

Started by
1 comment, last by Vilem Otte 6 years, 10 months ago

I need a script for a Play and a Quit buttons i already have the buttons set up i just need some script :)(In C#)

Advertisement

So, as I've created some games already in Unity, I will describe simple example of how I'd do it in Unity these days (and most likely will do it next time I'll use Unity for something):

Here is a simple example I put together in few minutes: https://otte.cz/random/MainMenu.rar

Short description: What you need is some GameObject in scene which will have script containing public functions that are handlers for buttons. The class holding these must derive from MonoBehaviour, like the one in the archive:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenuController : MonoBehaviour
{
    // Function called for button, must have 0 or 1 string argument at most, must be public
    public void NewGameHandler()
    {
        // Load another scene with "Game" name, scenes must be added in Build Settings!
        SceneManager.LoadScene("Game");
    }

    // Function called for button, must have 0 or 1 string argument at most, must be public
    public void QuitHandler()
    {
        // Exit the application
        Application.Quit();
    }
}

Now on the buttons, add a On Click record, where you attach (drag & drop, or just click + select) this game object with above-like MonoBehaviour attached. Next, select (from event drop down) the MonoBehaviour class name and under it there will be a function (NewGameHandler, QuitHandler)... note that the drop down has 2 levels, it is easy to miss it.

It is setup in the project in the archive, so feel free to use anything from it.

My current blog on programming, linux and stuff - http://gameprogrammerdiary.blogspot.com

This topic is closed to new replies.

Advertisement