And Half A Fish Games.

And Half A Fish
Games

Reaching for the Stars. Jun 23, 2014 - GUI.

I have had so much trouble getting the buttons & text (score etc) to work correctly in my game !

First, I had this curious problem where Unity would refuse to detect mouseover events on my buttons ...

It seems other people have had this problem as well, with Unity 2D. Some were able to fix it, others never got it working.
There were some suggestions about using Raycasting, but that didn't feel right to me ...

I then stumbled upon 'GUI Skin' and the 'OnGUI()' function ...
And fortunately, that did the trick for me !

What you do is, you create a new GUI Skin in the Projects folder, and then, you define a new custom style for every button you want to create in your menu.
You should also name that style, so that later on, you can refer to it again. I used 'Normal', 'Hover', and 'Active' background to attach the images for the inactive button, the button with mouseover, and the clicked button.

GUI Skin in the editor

In your code, you then check for button events with the GUI.button() funtion :

void OnGUI(){
    GUI.skin= Skin1;
    if( GUI.Button( new Rect(x,y,w,h), "someBtnTxt", "GUISkinStyleName")){
        //do sth
    }
} 


As simple as that !

Second, if you also want your button or label to scale correctly when you resize the game window, you should define a GUI.matrix :

GUI.matrix= Matrix4x4.TRS(
    Vector3.zero,
    Quaternion.identity,
    guiScalingFactor
);


The idea behind this is, that you design your menu assuming a certain game window resolution, eg/ 450x600 px. Then, whenever the window size is different from 450x600px (but still the same ratio !), you multiply your x,y,z scale from the inspector with that difference.
Eg/ my resized window is 900x1200 px >>> I need to multiply by (900/450)= 2.