Hello guys. My objective is to get same tagged objects and change their materials to the assigned one and after 3 seconds assign previous materials back.
Here’s how I try to manage it, but couldn’t. Can you help me?
public Material walls_Sand;
string assignedMaterialName;
void Update()
{
/////Find all objects contains "Obstacle" tag
Obstacles = GameObject.FindGameObjectsWithTag("Obstacle");
foreach (GameObject obstacle in Obstacles)
{
if(obstacle.GetComponent<MeshRenderer>() != null)
{
/////Get each objet's material name
assignedMaterialName = obstacle.GetComponent<MeshRenderer>().material.name;
/////Change each object's material to walls_Sand
obstacle.GetComponent<MeshRenderer>().material = walls_Sand;
}
}
///////////// W.A.I.T 3 S.E.C.O.N.D.S /////////////
foreach (GameObject obstacle in Obstacles)
{
if(obstacle.GetComponent<MeshRenderer>() != null)
{
/////Change each object's material to their previous materials by finding the same named materials in the library
obstacle.GetComponent<MeshRenderer>().material = (Material)Resources.Load(assignedMaterialName, typeof(Material));
}
}
}
Thank you for answer. The code I shared is actually a shortened version in order not to tire you guys.
So I’m not calling the codes in update on every frame. I wrote the codes inside of update because i needed to use “if(Input.GetKey(KeyCode.C))”. After pressing the “C” key, the if statement automatically closes itself by turning a boolean to true.
And there’s also a coroutine in between which counts for 3 seconds.
The problem is, my objects are above 100 and dynamic. I re-arrange them time to time. Therefore it’s impossible for me to assign and change every each one of them every time. So I’m calling them by their tag.
And as you mentioned some of my objects have more than 1 materials. So I still can’t imagine the codes.
If you have time can you please write your sentences in codes as examples.
Easiest would be a Arrays of Arrays of Materials, so a jagged array… check in google how such a thing works.
Here, honestly it’s easier to just write the code than to explain.
You can download the entire project and run that same scene and see it in action with Renderers of varying numbers of materials.
As long as you feed that an array of Renderers, it will feed you back an array of arrays of materials, one-to-one corresponding, so you would need to save the original array to restore it properly.
Look at the code that outputs what it found, which could be 1, 2, 3, whatever materials per original Renderer