- Home /
Change the texture on a material at runtime without creating an instance
I have a few objects in my scene that the user can change the main colour of the material via a colour picker script.
The Object (a ball) has 4 materials on it since the user can customise the balls colours and each of these materials except for the base is a transparant material. At first everything works as it should. The user picks a colour from the picker and it changes the colour of the material. So far so good.
Next I want to incorporate a new design. Rather than duplicating everything and have a new mesh with new materials (increasing draw counts and overheads), I thought I would just change the texture on the ball objects material. This would also mean that the colours the user had previously chosen would carry over to the new design.
However, as soon as I push the button to change the design, the materials on the ball object become instances and the colour picker no longer functions. I don't know why when I try to change the texture it changes the material to an instance of the original one.
Is there something/some concept I'm missing?
using UnityEngine;
using System.Collections;
public class BallSelector : MonoBehaviour {
public Texture[] hurricane;
public Texture[] cyclone;
string currentStyle;
void OnGUI()
{
if(GUI.Button(new Rect(Screen.width - 120, 20, 100, 50),"Hurricane"))
{
currentStyle = "Hurricane";
ChangeStyle(currentStyle);
}
if(GUI.Button(new Rect(Screen.width - 120, 80, 100, 50),"Cyclone"))
{
currentStyle = "Cyclone";
ChangeStyle(currentStyle);
}
}
void ChangeStyle(string style)
{
switch(style){
case "Hurricane":
renderer.materials[0].mainTexture = hurricane[0];
renderer.materials[1].mainTexture = hurricane[1];
renderer.materials[2].mainTexture = hurricane[2];
renderer.materials[3].mainTexture = hurricane[3];
break;
case "Cyclone":
renderer.materials[0].SetTexture("_MainTexture",cyclone[0]); //tried something else but same result
renderer.materials[1].mainTexture = cyclone[1];
renderer.materials[2].mainTexture = cyclone[2];
renderer.materials[3].mainTexture = cyclone[3];
break;
}
}
}
Answer by AndresBarrera · Jan 22, 2015 at 09:07 AM
Try using renderer.sharedMaterial. But this will modify the material for all your objects using it.
You sir are a legend. I knew it was probably something so simple.
Your answer
Follow this Question
Related Questions
Changing scrolling textures on a plane using transparency 1 Answer
So, what's the problem with this code? 1 Answer
Having a problem with the second material (on the same renderer) 0 Answers
How to reload a mainTexture to a mesh? 1 Answer
How to check if a Renderer has instantiated materials without instantiating them? 1 Answer