Umeer Rama
Umeer Rama

Reputation: 35

C# Unity 2D Game Menu isn't starting the game when the new game button is pressed

The game is supposed to start when the new game button is pressed, but unity starts the game when I press the left mousekey anywhere in the menu. I added the c# file as a component to the new game button, but it doesn't do the job either. This is the code I have:

using UnityEngine;
using System.Collections;

public class Newgame : MonoBehaviour {

    public void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
             Application.LoadLevel("TestScene1");
        }

    }
}

Upvotes: 1

Views: 588

Answers (3)

Adam H
Adam H

Reputation: 1573

The reason this is happening is that Input.GetMouseButtonDown returns true if the user presses the mouse button anywhere, not just on the GameObject that the script is attached to.

If you are using Unity 4.6 or above, Sundar Bons' answer is the best way to do it.

If not, you can use the OnGUI function:

OnGUI()
{
    if (GUI.Button(new Rect(10, 10, 150, 100), "New Game"))
        Application.LoadLevel("TestScene1");
}

If you use this method, be sure to change the hardcoded values when calling the Rect constructor to make sure the button is in the right place for your game.

Upvotes: 0

Sundar Bons
Sundar Bons

Reputation: 119

if you are using unity 3D 4.6 or above.

just create some public function

public void loadScene()
{
    Application.LoadLevel("TestScene1");
}

on click select the function you create.

add click event

Steps to add selected function

  1. add that script has the loadscene function to a gameobject.

  2. click (+)button in On Click(Button) shown in above img.

3.drag and drop the game object into the field that created.

  1. on next dropdown select your script and than your function

thats it you are good to go.

Upvotes: 3

DurdenSC
DurdenSC

Reputation: 1

Have you checked your build settings (File>Build Settings...) to make sure that TestScene1 has been added to the "Scenes In Build" section (and that the box is checked)?

Upvotes: 0

Related Questions