Loading texture asset via Script - C#

Hi. I’m using this tutorial and everything is going swimmingly except I can’t work out how to load up a texture onto the GUI. I have my texture in ‘Assets/Textures/UI’ with the name ‘logo.png’. How would I go about loading up this asset via code and then rendering it in the GUI?

(I’m using C#, by the way.)

You can’t load assets from somewhere in your asset path because Unity only includes Assets in your build that are used/referenced. The only exception are Resources folder. But watch out, assets in those folders will be included in your build no matter what you do with them. In streamed web builds those files get streamed first, all.

To load a texture for example just do something like this:

private Texture2D myGUITexture;
void Start()
{
    myGUITexture = (Texture2D)Resources.Load("Texturename.png");
}

You can place your texture at this path: Assets/Textures/UI/Resources/Texturename.png

In most cases it’s better to assign the texture to a public variable like chtngtr said. You have no control what and when the assets from Resources folder are loaded. It depends on your needs.

When you are loading the default path is “Assets/Resources” even if u dont have a folder named Resources unity ll look there. so if you want something to be loaded from runtime create Resources folder 1st. then place there wt you want to be loaded.

SO CODE WONT WORK IF YOU DONT HAVE THIS FOLDER

example:

your image png texture or wtever is at: Asset/Resources/Images/PNGs/MyPng

then use Resources.Load(“Images/PNGs/MyPng”)as Texture2D;

Look that i didnt use foward slash before Images and back slash doesnt work

Assign your texture(logo.png) for btTxtr in the inspector.

public Texture btTxtr;

void OnGUI() {
if (GUI.Button(new Rect(10, 10, 100, 50), btTxtr))
Debug.Log(“Clicked”);
}

Go through the unity reference manual.