- Home /
Best Practices for Modifying Core Components,Best Practice for Editing Default Components?
New user here, so I apologize if there's a simple answer here, but what is the best way to make a global change to core components in Unity?
I have a Spriterenderer. Spriterenderer supports receiving shadows. It is not enabled by default and there is no public bool that allows me to toggle this from the UI. As such, I need to implement the following code to Spriterenderer each object.
this.GetComponent<SpriteRenderer>().receiveShadows = true;
I'm not sure that throwing a script component onto every sprite in the game is the most elegant way to accomplish this. I can't create a new component and inherit from Spriterenderer either as it is sealed. Is there no way to simply append a bool to the core component? This component stuff is taking some getting used to and I'm a bit of a neat freak.
Interesting question. Is this receiveShadows variable being even serialized? If so you can set these in OnValidate call (editor only)
#if UNITY_EDITOR
void OnValidate () {
foreach( var sr in FindObjectsOfType<SpriteRenderer>())
{ if(sr.receiveShadows==false) sr.receiveShadows = true; }
}
#endif
existing in some single scene maintainer script. It's Not ideal, but better that hundreds of scripts doing the same job.
This is a perfect solution that does exactly what I needed. It's even better than I expected because it does not need to be executed at runtime. A single execution of the code is enough to set the properties persistently inside the scene.
Thank you so much!
You're welcome :) But remember to build your project and make sure these will persist! Because otherwise this isn't done yet
Really interesting question.
Has your sprite actually received shadows when you enabled receiveShadows
? Because I think you also need a special shader that allows receiving shadows for it to work (according to this forum thread). Note that this forum thread also mentions that if you switch into debug mode of the inspector, you can turn on the receiveShadows
property.
However, none of this solves your original question. I think that SpriteRenderer
only has receiveShadows
, because it inherits it from Renderer
, but it should not actually have it, so Unity hides it with a custom inspector component.