- Home /
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.
Answer by robertbu · Apr 15, 2014 at 04:07 PM
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.
Thank you for replying but for this you must attach Renderer with you object, while the one that I cam using has none, anyways I solved it and will post the answer.
You wrote:
How can I change the Texture of a GameObject?
This implies that you already had a texture on the object and therefore a Renderer component. You can as you indicate dynamically add a Renderer, but it might be cleaner and easier to setup a default renderer and material on the object and only change the texture at runtime.
Your answer
![](https://koobas.hobune.stream/wayback/20220613142740im_/https://answers.unity.com/themes/thub/images/avi.jpg)