I am writing code for a GUI button, and when both the mouse is over the button (OnMouseEnter/Exit is what I am using) and the mouse is clicked (Input.GetMouseButton(0)) I want to load the next scene. The click part is giving me no trouble, but it is the Enter/Exit part that is not working. I would like to know if I am doing something wrong, or some other way to do both in one (as this is the only way I could find to complete the task). Any help is appreciated!
Code is in C#
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class Level1Button : MonoBehaviour {
private bool mouseHover;
void Start()
{
mouseHover = false;
}
void Update ()
{
if (mouseHover && Input.GetMouseButton(0))
SceneManager.LoadScene ("Level 1");
}
void OnMouseEnter()
{
mouseHover = true;
}
void OnMouseExit()
{
mouseHover = false;
}
}
Is this for the UnityEngine.UI system or GUI.Button rect or is it just a mesh you’re applying this script to?
Also there’s nothing else really wrong with this script, it should work fine if this is for a 3D text mesh or mesh in particular.
SceneManager.LoadScene(“Level 1”) should maybe be:
SceneManager.LoadScene(“Level 1”, LoadSceneMode.Single);
or that’s probably not it because it would default to that anyway.
Hmm did you remember to add the scene you are loading to into the File>Build Settings list?
I have discovered a very simple way to use a button to activate a scene change. It uses IPointerDownHandler. I will post the code below for anyone else who would like it.
Place the code on the GUI.Button you would like to use
Code is in C#
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;
public class Level1Button : MonoBehaviour, IPointerDownHandler //Make sure that you add this after MonoBehaviour or this WILL NOT work
{
public void OnPointerDown (PointerEventData eventData)
{
if (Input.GetMouseButtonDown (0)) //0 can be changed with 1 or 2, 0 is left click, 1 is right click, 2 is middle click
SceneManager.LoadScene ("Level 1");
}
}