changing UITexture of A GameObject

Hi, I’m new to Unity so I don’t know how to do the basic stuff in unity. How can I change the Texture of a GameObject? I’ve a png image, its name is stored in a string, and I want to change the Texture of my GameObject with that png image.

string dustTextureName = “Animal-Cat.png”; // name of the PNG image
GameObject dustTexture; // public GameObject in which UITexture is set shown in Inspector
dustTexture.GetComponent().mainTexture = dustTextureName; // this is the line where am stuck

Help me out.

You need to do one of two things. First you can deal with your texture directly. Do at the top of the file you would put.

public Texture tex;

After attaching your script to a game object, select that game object and you will see the ‘tex’ variable in the inspector. You can click on the target symbol next to ‘tex’ and set the texture or you can drag and drop a texture onto the ‘tex’ variable. This will link this variable to a texture in your project. Then to change the texture in code, you just have to:

renderer.material.mainTexture = tex;

The second solution is to put your texture in the Assets/Resources folder. It must be inside this folder to work. Then you can use Resources.Load() to load your image from a string:

go.renderer.material.mainTexture = Resources.Load(dustTextureName, typeof(Texture2D));

While I don’t think it is what you are asking, if you are trying to load the image from outside your Unity project (elsewhere on the machine or on the net), you can use the WWW class.