- Home /
Can't get tagged objects to change material
I am trying to change the material on multiple objects by pressing a button. Unfortunately I have only succeeded in making one object change material. I'm sure its something simple, but I just can't see it. Here's my current script. Any help would be appreciated.
#pragma strict
var materialchange1 : Material;
function Update () {
if (Input.GetButtonUp("mat")) {
GameObject.FindGameObjectWithTag("score").GetComponent(Renderer).material = materialchange1;
}
}
Answer by RobAnthem · Feb 09, 2019 at 04:24 PM
Umm, FindObjectWithTag does exactly as it says "Find Object" a single object. It will stop searching after that. What you want is this...
GameObject[] objs = FindObjectsWithTag("score");
foreach (GameObject obj in objs)
{
Renderer r = obj.GetComponent<Renderer>();
if (r)
{
r.material = materialchange1 ;
}
}
Sorry it's in C#, but that should be easy to fix.
Answer by AbubakrKhan · Feb 09, 2019 at 04:33 PM
Go to button on click event and drag the object of which you want to change the material and choose MershRenderer.SharedMaterial then add the material there u want to add. You can do it like that simple.
This isn't dynamic at all. It would work, but I think he's looking for something that doesn't require inspector setup. Hence my solution was just the proper version of what he was already trying to do.
there are many ways to do it, i suppose it would help him knowing the multiple ways of doing the same thing.
Your answer

Follow this Question
Related Questions
How do perform the operations as per the commands at client side in socket unity? 0 Answers
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
2d camera help! 0 Answers
On Trigger Stay 1 Answer