0

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));
Dez Boyle
  • 41
  • 6
  • this answers your question: [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ňɏssa Pøngjǣrdenlarp Jun 19 '22 at 17:47

1 Answers1

0

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).

Theraot
  • 31,890
  • 5
  • 57
  • 86
  • Thank you so much! I'm glad I don't need to use strings to access properties. I understand inheritance and casting but I'm still relatively new to the class structure of Godot. – Dez Boyle Jun 19 '22 at 17:55
  • @DezBoyle what extends what is in the documentation (the documentation page of each class says at the top what it extends and which build-in classes extend it). If you prefer a tree, you can find that too, see [Inheritance class tree](https://docs.godotengine.org/en/stable/development/cpp/inheritance_class_tree.html). Regarding C# what it is really missing is examples (edit: ideally it show the members in language specific syntax too). But it is not hard to figure out. – Theraot Jun 19 '22 at 18:06