- Home /
GameObject to Texture
Hi,
I have a folder, containing several PNG images. I need them to be used as a background of a GUI.Box and they will be changed at runtime.
For example. I have 3 buttons. An image name is attached to every button. When pressing it, it should tell Box to use this image as BG.
Is there a way to load this images as textures using their names?
Answer by robertbu · Feb 02, 2014 at 10:47 PM
Simply create public Texture variables and change which one is used based on your button. As an example. Attach it to an empty game object. Then drag and drop textures onto the 'tex1', 'tex2', and 'tex3' variables in the Inspector:
#pragma strict
var tex1 : Texture;
var tex2 : Texture;
var tex3 : Texture;
private var currTex : Texture;
function Start() {
currTex = tex1;
}
function OnGUI() {
GUI.DrawTexture(Rect(0,0, Screen.width, Screen.height), currTex);
if (GUI.Button(Rect(0,0,100,50), "Use Texture 1")) {
currTex = tex1;
}
if (GUI.Button(Rect(0,75,100,50), "Use Texture 2")) {
currTex = tex2;
}
if (GUI.Button(Rect(0,150,100,50), "Use Texture 3")) {
currTex = tex3;
}
}
Note if you really want to dynamically load the textures, you can place your images in the Assets/Resources directory and use the Resources.Load() function to load them.
I am happy to say that it was successfull.
BGTexture = (Texture)Resources.LoadAssetAtPath("Assets\\Resources\\FileName.PNG", typeof(Texture));
Worked perfect.
Answer by nTu4Ka · Feb 03, 2014 at 10:22 AM
Note if you really want to dynamically load the textures
I think this is what I need. I've seen someone's opinion that using "Resources" directory is not a very good idea. Don't know why, though. But tried to avoid it.
Thanks for pointing in the right direction.