- Home /
Create GUI Texture using GUI Layout
How can I display a texture onto the screen without using a Rect
? I want to use GUILayout
but it seems the only option for that is to use a GUI Box which makes my texture look like this:
See the box around the texture? I don't need that.
I can achive the look I want with a GUITexture component (from GameObject > Create Other > GUI Texture) like this...
...but I want to create it through script.
Any ideas? Thanks in advance.
Answer by Professor Snake · Jul 02, 2013 at 09:49 PM
Use a GUISkin with a custom style.
Create a new GUISkin by right clicking and selecting Create->GUI Skin. Then, create a new entry in its Custom Styles and set its Image Position setting to ImageOnly:
Then, draw your heart with a style override.
var mySkin:GUISkin;
function OnGUI(){
GUI.skin=mySkin;
GUILayout.Box(myRect,myTexture,"nameOfCustomStyle");
}
Answer by VinhLee · Feb 21, 2017 at 02:21 PM
Create a object with class name : item.cs
public class Item
{
public string Icon;
public Rect rect;
public Sprite Sprite
{
get
{
Texture2D t2D = Resources.Load<Texture2D>("2D/icon/" + Icon);
Sprite sprite;
if (t2D != null)
{
sprite = Sprite.Create(t2D, rect, new Vector2(0.5f, 0.5f));
sprite.name = Icon;
return sprite;
}
else
return null;
}
}
public Texture2D TextureIcon
{
get
{
Sprite sprite = Sprite;
if (sprite != null)
{
Rect r = sprite.rect;
Texture2D icon = new Texture2D((int)r.width, (int)r.height);
Debug.Log("Rect:" + r);
icon.SetPixels(sprite.texture.GetPixels((int)r.x, (int)r.y, (int)r.width, (int)r.height));
icon.Apply();
return icon;
}
return null;
}
}}
And Draw sprite at file ItemWindow.cs
public class ItemsWindow
{
void OnGUI()
{
Item item = Database.ItemData[i];
if(item.Sprite != null)
GUILayout.Label(item.TextureIcon,GUILayout.Width(96));
}
}