Newbie question: draw a red button by script

Hi all,

I’am having a hard time finding a way to create a custom button via script. I know you can create a new guiskin in the assets menu, but I want to do it dynamically.

Let’s say for example that a player will have a red button and another a random colored button, And the style will have to be done via script depending on the game circunstance.

How can I do a custom gui purely via script?

Thanks

A GUI skin is a collection of GUI styles. You can create a new GUI style in script:

GUIstyle buttonStyle = new GUIStyle(GUI.skin.button); // Based off default button style.
buttonStyle.normal.background = randomNormalButtonBackgroundTexture;
buttonStyle.hover.background = randomHoverButtonBackgroundTexture;
...
GUI.Button(rect, "Button Text", buttonStyle);

Set the style states (normal, hover, active, etc.) that you need for your application.

If you only need one texture, you can use an alternate form of GUI.Button():

GUI.Button(rect, "Button Text", myRandomTexture);

Thanks for the quick answer.

Another question: How do I change the border of the button, so that it has no round corners? (via script again)

And how do you create a texture with a random color using js?

Thanks

Use a different texture for your button style. The textures in the default GUI skin use rounded corners.

If you know the colors ahead of time, in your script you could define a public array of Texture2D’s. Then create separate textures for each color, and in the inspector assign the textures to the array. When you set up the GUI style, randomly choose one of the textures from the array.

If you’ll only have one button of this type on the screen, you can use SetPixels() to change the texture directly. If you have multiple randomly-colored buttons onscreen, you’ll want to create a texture for each and use SetPixels() to set their colors.

Can I Load the texture dynamically, like from my website? So then I could use in the button?

Thanks for the help!

Use WWW(). The example on the manual page shows how to load a texture. And happy to help!