Getting and setting a Texture via a script using Material

I have a set of PNGs which I wish to use as textures for a Sphere. I would like to update my the texture depending on the camera movement, however the only issue I have had so far is getting the material of the sphere. This is my inspector information for the sphere Imgur: The magic of the Internet

The material is testMatLeft.

In my script, in the Start Function I have the following lines:

GameObject LeftGObj = GameObject.Find(“LeftSphere”);
leftMat = LeftGObj.GetComponent();

however this returned null. I’ve tried a couple of other differences but to no avail, am I doing something massively wrong?

leftMat = LeftGObj.GetComponent<Renderer>().material;
1 Like

Thank you. And using this function should be enough right Unity - Scripting API: Material.SetTexture ?

I have put the nameid value as 0.

Yeah, or you could simply assign the material’s mainTexture as one of your PNGs :

public Texture2D myPng;

leftMat = LeftGObj.GetComponent<Renderer>().material.mainTexture = myPng;

It really depends on the shader you are using though.

2 Likes