I got this code from somewhere else.
foreach(Renderer r in target.parent.GetComponentsInChildren()) {
foreach(Material M in r.materials) {
M.color = setColor;
}
}
How do I make it so it only changes color to a certain material?
The material name is “Primary Color”, How do I refer to them…?
can I use string? or should I use an Index?.
1 Answer
1
If your script is on a gameobject, you could just make a material property and drag in the material reference in the inspector and then check in your loop if the material in the renderer is the same material.
Example:
public Material material;
public void YourFunction() {
foreach(Renderer r in target.parent.GetComponentsInChildren()) {
foreach(Material M in r.materials) {
if(M == material) {
M.color = setColor;
}
}
}
}
Edit: Actually, if they use the same material, you only need to change the color of the reference:
public Material material;
public void YourFunction() {
material.color = setColor;
}
Now, if they don’t use the exact same material and rather its own material instance based on the same material; then I would check for the name of the material instead.
The first method and the second did not work. Actually, the material are instanced, since Every player would have a different coloring. (Object group of my tank for example, which uses multiple material, and each player will have different team coloring.) How do I check for the name? Wouldn't doing that will also change other player's instance since their name is "MaterialX (Instance)" too?.
– GekigengarWell, you specify to only change color of materials of the target, so as long as the target variable is only one player, you only change color of that player. foreach(Renderer r in target.parent.GetComponentsInChildren() { foreach(Material M in r.materials) { if(M.name == nameToCheck) { M.color = setColor; } } }
– GameVortexIt works now!, Using the string comparison. I need to add material.name + " (Instance)" to get the stuff working :D Thank you! May you be blessed good sir~!
– GekigengarGlad you figured it out =)
– GameVortex