2

I've been having problems with my code for unity. I'm using C Sharp and Unity 5.0.2f Personal Edition. Here's my code:

using UnityEngine;
using System.Collections;

public class ButtonEvent : MonoBehaviour {
    public void LoadScene(int SceneToChangeTo){
        Application.LoadLevel (SceneToChangeTo);
    }
}

This should change the to an integer scene but when I go to the button.onclick() in the inspector and add the script nothing comes up about changing scene (Note: The script is under "_Manager" (An empty GameObject))

1
  • Make sure you add your scene in Build Setting
    – dev-masih
    Commented Jun 7, 2015 at 13:25

2 Answers 2

1

Add a listener for your button and make sure you put a value in numberOfLevel variable and assign your button to MyButton in the inspector or you will get a null reference exception

[SerializeField] private Button MyButton = null; // assign in the editor
public int numberoflevel;

void Start() { MyButton.onClick.AddListener(() => { changeScene(numberoflevel);});
}

 public void LoadScene(int SceneToChangeTo){
        Application.LoadLevel (SceneToChangeTo);
    }
3
  • Thanks but I found the LoadScene() I was just messing around trying to find it and it turned out it was right in front of my eyes Commented Jun 7, 2015 at 15:33
  • actually, what would I have to do to make a button that could exit the game Commented Jun 7, 2015 at 15:37
  • in my answer i made a button that changed scenes so instead of calling change scene make another method for exit like this void Start() { MyButton.onClick.AddListener(() => { quit();}); } public void quit(){ Application.Quit(); } Commented Jun 8, 2015 at 5:20
1

use this code:

        using UnityEngine.SceneManagement;
///***///
        public void LoadGameLevel(int SceneToChangeTo)
        { SceneManager.LoadScene(SceneToChangeTo);
        }
    //or
        public void LoadGameLevel(string SceneName)
        { SceneManager.LoadScene(SceneName);
        }

note: Worked in OnMouseDown() and Unity Ui and other

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.