- Home /
How to change specific material shared among specific children.
Hi there, I am encountering some trouble in my code and was hoping someone would be kind enough to assist me in wrapping my head around this.
The scene:
1 game-object with 5 child-objects, with differing materials.
1 child with paint.
2 children with plastic.
2 children with metal.
The goal:
To attach a script to the parent object, "The Thing" and to be able to edit ONLY the children who share the black-plastic material.
I've set up a few buttons, when clicked, it will run the script that's attached to the parent object:using System.Collections; using System.Collections.Generic; using UnityEngine; public class PaintChange3 : MonoBehaviour { Renderer[] children; public Material[] plastics; // Use this for initialization void Start () { //children is a reference to the renderers children = GetComponentsInChildren<Renderer>(); foreach (Renderer rend in children) { //make array of all materials in renderer Material[] materials = rend.materials; } } //Changes Plastic public void ChangePlastic(Material matPlastics) { foreach (Renderer rend in children) { var mats = new Material[rend.materials.Length]; for (var j = 0; j < rend.materials.Length; j++) { mats[j] = matPlastics; } rend.materials = mats; } Debug.Log("Changed Plastics, Maybe?"); } }
The problem with my script is that it affects every child's renderer, I do not know how to target just the plastic children. How should I approach this solution?
Thank you again!
Answer by II_Spoon_II · Nov 13, 2018 at 08:42 PM
public void ChangePlastic(Material matPlastics)
{
foreach (Renderer rend in children)
{
var mats = new Material[rend.materials.Length];
for (var j = 0; j < rend.materials.Length; j++)
{
//add a condition to check if the current material is blackPlastic
if (mats[j]==blackPlasticMaterial)
{
mats[j] = matPlastics;
}
}
rend.materials = mats;
}