- Home /
Make GUI Button's size fit texture?
Hi, i'm new to Unity and now having some troubles with making GUI stuffs. I want to make a menu consisting of some simple buttons aligned center of the menu. I don't want to fix the position or size of buttons (like setting it x:20, y:20, w:200, h:50 or something like that). All I want is to make size of the buttons and box and any further controls I may add fit the textures given. By now I only found some examples which use fixed width, height for buttons/boxes. Anyone have a solution for this? Sorry if i'm not making it clear enough, i'm not good at expressing things :(
Answer by robertbu · Mar 22, 2013 at 04:57 AM
Just use the texture width and height when you specify the button. Example:
var tex : Texture;
function OnGUI() {
if (GUI.Button(Rect(50,50,tex.width, tex.height), tex))
Debug.Log("Button Pressed");
}
Or maybe what you have more in mind is the GUILayout class. You can use GUILayout.Button() instead of GUI.Button().
Ahh I got the first idea. So I will need to load the texture using Resources.Load("myTexture") is that right? About GUILayout class, yes I'm actually using GUILayout.Button() ins$$anonymous$$d of GUI.Button() but I set its texture in a GUISkin then write it like this GUI.skin = $$anonymous$$yGUISkin;
which doesn't seem to work as the button's size scaled down to fit its text.
UPDATED: it works with the skin now. +1 for re$$anonymous$$ding me to get the texture's width and height :D Ty so much!
Answer by Brastik · Mar 22, 2013 at 07:03 AM
I get it working with the GUISkin by retrieving the width
and height
of the button's texture that I attached in the skin. In details:
GUISkin MenuSkin = (GUISkin)Resources.Load ("MenuSkin");
GUI.skin = MenuSkin;
GUILayout.BeginArea (new Rect (0, 0, Screen.width, Screen.height));
int buttonNormalWidth = MenuSkin.button.normal.background.width;
int buttonNormalHeight = MenuSkin.button.normal.background.height;
GUILayoutOption[] options = {GUILayout.Width(buttonNormalWidth),GUILayout.Height(buttonNormalHeight)};
GUILayout.Button ("Game",options);
GUILayout.EndArea ();
Hope that helps someone :D
Your answer
Follow this Question
Related Questions
Make more buttons appear, on button click. 1 Answer
Null reference exception[SOLVED] 1 Answer
GUI texture to fit the screen at any resolution? 4 Answers
Button Texture Issues?? 1 Answer
proper inventory system issue.. 1 Answer