- Home /
Change material at runtime - I must be overlooking something
Hi, i'm trying to have a dynamic cloud system of sorts wherein the cloud color and alpha changes depending on time of day. I have the system set up as below. I've looked through several posts on this topic but nothing seems to be working for me. I'm pretty sure i'm overlooking something obvious - could someone please tell me what is going wrong here?
I'm using Unity 2019.3, and URP as the renderer.
My code is as below:
public material SkyClouds;
private material cloudsMat;
void Start()
{
cloudsMat = SkyClouds;
cloudBox = GameObject.CreatePrimitive(PrimitiveType.Sphere);
cloudBox.transform.localScale = new Vector3(1000, 500, 1000);
cloudBox.GetComponent<Renderer>().material = cloudsMat; // works fine upto here, I get the initial cloud material set and visible
}
void Update()
{
cloudAlpha = 0.1f * timeofday; // I have a separate variable that controls time of day
cloudsMat.color = new color(redfactor * timeofday,1,1,cloudAlpha); //basically a calculation that changes redness and transparency depending on time of day
cloudBox.GetComponent<Renderer>().material = cloudsMat; //this is the solution I found on most posts, but it doesn't work for me. The material color or transparency does not change at all.
//I have also tried cloudBox.GetComponent<Renderer>().material.SetColor("_BaseMap", new color (1,1,1,cloudAlpha) and using materialpropertyblock, both don't work for me. What might be happening is if I look in the inspector, the game has created a separate object called "Sphere" - maybe the code does not refer to this "Sphere" object at update time? It sets the material fine at "Start", but nothing changes at "Update"//
}
Answer by CrazyNito · Sep 30, 2020 at 09:46 PM
Try accessing with
renderer.materials[0]
So it will be
renderer.materials[0].SetColor(redfactor * timeofday,1,1,cloudAlpha)
Answer by mikeMxM · Oct 01, 2020 at 08:59 PM
Thanks for your reply. It appears that I had to use "_BaseColor" instead of "_BaseMap" because of the shader I was using (URP simple lit). It's working now.
Your answer
![](https://koobas.hobune.stream/wayback/20220613012854im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Accessing material.color removes the material... 1 Answer
Material doesn't have a color property '_Color' 4 Answers
Android is rendering dark materials as white 0 Answers
How to change or set the Ground and Sky Tint color of a Procedural Skybox through script? 1 Answer
Why is my Cube appearing Grey ? 3 Answers