I'm just trying to set the color of a material at runtime. The C# docs are sparse.
MaterialOverride.Set("albedo_color", new Color(1f, 1f, 1f));
CodePudding user response:
That should be (tested):
((SpatialMaterial)MaterialOverride).AlbedoColor = new Color(1f, 1f, 1f);
You would get NullReferenceException
if you let SpatialMaterial
uninitialized. You would get a InvalidCastException
if it isn't a SpatialMaterial
(it could be ShaderMaterial
).
It happens that MaterialOverride
is defined as Material
, and there are a few classes that extend (inherit from) Material
. Namely: CanvasItemMaterial
, ParticlesMaterial
, ShaderMaterial
, and SpatialMaterial
. And, of course, AlbedoColor
is a property of SpatialMaterial
.
So C# does not know which of these MaterialOverride
actually is, which is why we cast. There are other ways to cast in C#, see Casting and type conversions (C# Programming Guide).