Language

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

1 Reply

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:

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

Hint: You can notify a user about this post by typing @username

Attachments:
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.