- Home /
Having trouble with getcomponentsinchildren.
Having a bit of trouble with using GetComponentsInChildren.
private Material[] cachecolours;
void Start ()
{
//...
cachecolours = transform.GetComponentsInChildren<Material>();
}
void Update ()
{
foreach (Material colour in cachecolours)
{
colour.color = new Color(cs, cs, cs);
}
}
I want to change the colour of the materials of each child of my object but I keep getting these errors:
ArgumentException: GetComponent requires that the requested component 'Material' derives from MonoBehaviour or Component or is an interface.
and
NullReferenceException: Object reference not set to an instance of an object
I believe the second is due to the first but I can't figure out how to change the colour of each child in turn.
cs is assigned a float value I just excluded that part of the code.
Answer by gjf · Sep 26, 2016 at 07:26 PM
"In order to get the material used by an object, use the Renderer.material property."
Could you explain a bit better please. I've tried everything I could think of and couldn't get it to work. GetComponenentsInChildren seems to give a Component[] output but I want $$anonymous$$aterial[]
IIRC changing the variable to type Component[] and getting the component then doesn't allow me to get the material.color I need.
$$anonymous$$aterial
isn't a component - Renderer
is. get the Renderer
component then iterate thru those setting the color as required... something like (not tested)
private Renderer[] _cacheRenderers;
void Start ()
{
//...
_cacheRenderers = transform.GetComponentsInChildren<Renderer>();
}
void Update ()
{
foreach (var renderer in _cacheRenderers)
{
renderer.material.color = new Color(cs, cs, cs);
}
}
Ok thanks, I'll try it out tomorrow and let you know if I get it working :)
Your answer
Follow this Question
Related Questions
grab weapon script problem 1 Answer
Storage of children references efficiency 1 Answer
importing a blender model amd making it look the same 0 Answers
Unet Material color change do not work. 0 Answers