- Home /
Fading Out Objects/3D Models In The Editor
I'm attempting to write a script that behaves similar to the Canvas Group component but for 3D models. The script works during runtime, but I'd also like to use it during edit mode. Here's the OnValidate method:
void OnValidate () {
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer r in renderers) {
if (r.sharedMaterial == null) {
continue;
}
Material mat = new Material(r.sharedMaterial);
Color color = mat.color;
color.a = alpha;
mat.color = color;
r.sharedMaterial = mat;
}
}
This works as intended until I hit "Apply" and then all the renderers in the prefab lose their material references. I'm making a new material because Unity complains about setting the material properties on prefabs AND I'm duplicating the shared material so that other objects using the material aren't affected.
Here's the full script for reference:
public class AlphaGroup : MonoBehaviour {
[Range(0.0f, 1.0f)]
public float alpha;
RendererData[] _data;
float _lastAlpha;
void OnValidate () {
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer r in renderers) {
if (r.sharedMaterial == null) {
continue;
}
Material mat = new Material(r.sharedMaterial);
Color color = mat.color;
color.a = alpha;
mat.color = color;
r.sharedMaterial = mat;
}
}
void Awake () {
UpdateRendererList();
}
void Update () {
if (_lastAlpha != alpha) {
for (int i = 0; i < _data.Length; i++) {
Color color = _data[i].renderer.material.color;
color.a = _data[i].originalAlpha * alpha;
_data[i].renderer.material.color = color;
}
_lastAlpha = alpha;
}
}
public void UpdateRendererList () {
Renderer[] renderers = GetComponentsInChildren<Renderer>(true);
_data = new RendererData[renderers.Length];
for (int i = 0; i < _data.Length; i++) {
_data[i] = new RendererData(renderers[i], renderers[i].material.color.a);
}
}
class RendererData {
public Renderer renderer;
public float originalAlpha;
public RendererData (Renderer renderer, float originalAlpha) {
this.renderer = renderer;
this.originalAlpha = originalAlpha;
}
}
}
Your answer
Follow this Question
Related Questions
Changing all materials of selection from code 0 Answers
Fuse objects visually when close to each other Shader/ Effect 2 Answers
Renderers with multiple materials 0 Answers
Model doesn't support material 0 Answers