OnMouseDown

This really shouldn’t be an issue, but with my code OnMouseDown() is messing up:

  1. I’m not getting a single error in the console
  2. No code I put in it will run (of course I get no errors though)
  3. ONLY debug statements work properly in it so it IS going through the method.

I have a work around OnMouseUpAsButton() so it’s not TOO big of a deal, but I really want to know wtf is wrong here cause the code as far as I can tell is fine.

using UnityEngine;
using System.Collections;

public class GUIScript01 : MonoBehaviour
{
    public Texture2D baseImage;
    public Texture2D overImage;
    public Texture2D downImage;
    public string loadsLevel;

    void OnMouseOver()
    {
        this.gameObject.guiTexture.texture = overImage;
    }

    void OnMouseExit()
    {
        this.gameObject.guiTexture.texture = baseImage;
    }

    void OnMouseDown()
    {
        this.gameObject.guiTexture.texture = downImage;
        Debug.Log("In OnMouseDown()");
    }

    IEnumerator OnMouseUpAsButton()
    {
        audio.mute = false;
        audio.Play();
        yield return new WaitForSeconds(audio.clip.length);
        if (loadsLevel != "")
        {
            Application.LoadLevel(loadsLevel);
        }
        else
        {
            Application.Quit();
        }
    }
}

Well, it’s a matter of implementing some kind of ‘MouseHeld’ detector. In this case, it should be as simple as setting a flag to ‘true’ whenever the mouse is held down. So, in your OnMouseOver:

if(Input.GetMouseButton(0))
{
    this.gameObject.guiTexture.texture = downImage;
} else {
    this.gameObject.guiTexture.texture = overImage;
}

This will check to make sure that the mouse button has been pressed.

You can only access the GUI from inside OnGUI();

Try this:

void OnGUI() {
	if (Input.GetMouseButtonDown(0)) {
		this.guiTexture.texture = downImage;
	}
}

There are many ways you can change this to make the code cleaner, for example setting flags, sending messages etc. for the GUI to pick up when it renders. Unlike my basic example, you shouldn’t handle input inside OnGUI so you’ll need to setup your own system for converting input to the GUI.