How to find all gameobjects that use the same material and change it?

Hi!
Im a noob at programming, and im having some trouble with this simple task…

What i wanted is to find all gameobjects that use a specific material, and change it to another different material.

So in the script ive done, i have to put by hand the material i want to find and the material i want it to change to, and then in play time when i press space it was supposed to change to the new material but its not happening.

Could someone help me?

Thank you so much!!!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script_ChangeMaterials: MonoBehaviour

{

	public Material materialtochange;
	public Material materialchanged;
   	private Renderer rend;
   	private Material[] mats;
    
	void Update()
	{
		if (Input.GetKeyDown("space")) 
		{
			Renderer[] rend = FindObjectsOfType(typeof(Renderer)) as Renderer[];


			for( int i = 0 ; i < rend.Length ; i++)
			{
				if(rend*.material == materialtochange)*
  •  		{*
    

_ rend*.material = materialchanged;_
_
}_
_
}_
_
}_
_
}_
_
}*_

I believe a way to do this is search through all GameObjects in the scene looking for the material you want to replace on each individual GameObject. When a GameObject has that material you’re looking for then replace the material on that GameObject.

The code looks like you want to search for all the Renderers in the scene so you can change the material attached to them but each Renderer is a component of a Gameobject. I believe you need to access each GameObject’s Renderer through each individual GameObject and see if the material on the Renderer of each GameObject matches the material you want to replace. Then you can replace it.

You may also be getting an error from declaring rend to be a Renderer at the beginning of your code and later on line 18 trying to make it an array when you didn’t declare it as an array on line 11.

This Unity Documentation link will get you closer to achieving your goal:

Go through the videos and scripts of the aspects of code you may not be familiar with. It looks to me you’re headed on the right path from the way you’re thinking about the problem but may need to freshen up on syntax and how Unity and GameObjects are structured. Going through the beginner and intermediate script tutorials may take a little while but it should be shorter than going through a C# book. As you mentioned you’re new to programming going through a C# book would be a rewarding experience also. But you don’t have to do all that before solving your problem. You can solve your problem in short order by going through some of the script tutorials.

And don’t be afraid of getting things wrong or get frustrated if something’s not compiling. When I started out it took me three hours to discover I had a missing closing bracket. That ruined my day because I was sooo frustrated and I didn’t need to be.