- Home /
Question by
vleonc · May 23, 2018 at 03:55 AM ·
c#materialsparent-child
How to change children's material of gameobject on trigger?
Hi guys,
So I have a gameobject that is triggered, on this trigger I want it to change the material of its children or of the children of another gameobject.. I have no idea how to do this!
Basically og1 is triggered and I want Lighthouse and its children's material to be changed on this trigger.
Hoping you guys can help!
Here's a terribly wrong version of my code:
public Material newMat;
public GameObject objectToChange;
void OnTriggerEnter (ChangeMaterial newMat)
{
Renderer[] children;
children = GetComponentsInChildren<Renderer>();
foreach (Renderer rend in children)
{
var mats = new Material[rend.materials.Length];
for (var j = 0; j < rend.materials.Length; j++)
{
mats[j] = newMat;
}
rend.materials = mats;
}
}
}
screen-shot-2018-05-23-at-15136-pm.png
(17.3 kB)
Comment
Answer by spilat12 · May 23, 2018 at 04:55 PM
I just checked your script and can verify that it works well. Perhaps, you did not add rigidbodies to your objects?
Here's a slightly optimized version of your script:
public Material newMat;
public GameObject objectToChange;
Renderer[] children;
void Start()
{
children = GetComponentsInChildren<Renderer>();
}
void OnTriggerEnter()
{
foreach (Renderer rend in children)
{
var mats = new Material[rend.materials.Length];
for (var j = 0; j < rend.materials.Length; j++)
{
mats[j] = newMat;
}
rend.materials = mats;
}
}
Yes, thank you so much! I forgot to reply sorry, knee deep in assessments. Appreciate the help mate!
Your answer
