C# Script, Set Texture of gameObject

Simply, I’m trying to make a C# script where I press a key and it sets the texture of an object(Lets say a simple basic cube with the script attached) to a given texture eg. blahblah.png

if (Input.GetKey(KeyCode.DownArrow))
// CODE GOES HERE: Set this Current game Objects texture to “blahblah.png”

I cannot for the life of me find any article on the internet to do this in C#. I’ve been through the unity docs and other youtube tutorials and so far it’s been irrelevant or javascript with syntaxes that don’t easily convert to C# or people just redirect people to look at the unity docs which don’t help.

Any help is massively appreciated.

Well, there are actually a lot of examples on how to do this… And Javascript syntax only differs in a few small things really, so it would be good to brush up on those differences.

As for how to do it, well firstly, you need to declare a variable that can accept a Texture.

In C#, this is simply written as “[modifier] Texture [name];”.

Once you have the variable, you can use it’s name as the input for “renderer.material.mainTexture”. And as long as the variable is set to “public”, then you can choose a texture for that variable through your Inspector.

It should look something like this:

public class somethingWhatever : MonoBehaviour {
public Texture cheese_diffuse;
public Texture cheese_diffuse2;
	void Update () 
             if (something)
	          renderer.material.mainTexture = cheese_diffuse;
                  renderer.material.mainTexture = cheese_diffuse2;

It sounds like you need to start going through the Unity beginner lessons and start learning! :slight_smile:

You need the reference to the texture you want, so a public Texture2D variable which you assign the texture to in the inspector. Then you access the renderer and material of the object and set the mainTexture to be your texture.

Put this at the start of the class script.

// Assign value in the inspector
public Texture2D textureToUse;

Then you need to set the texture of the material after you press the key.

renderer.material.mainTexture = textureToUse;

This of course requires the renderer to be on the same GameObject as the script component.