Garbage Collection in my Script

Hello, I’m trying to resolve some memory usage in my Profiler
And this code is using a lot of memory I think because it’s using many times in the scene in different objects.
Please try to help, I’m not so good at scripting :slight_smile:

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

public class MatSwitch : MonoBehaviour {

	public Material mainMat;
	public Material newMat;
	public Renderer childrens;

	public float max;

	static float t;

	public float thres;

	public bool isMatNew;

	public bool access;

	public static bool zeroSlider;

	public void Start()
	{
		isMatNew = false;

		thres = newMat.GetFloat("_Threshold");
	}
		
	public void Update () {
		Renderer[] childrens;
		childrens = GetComponentsInChildren<Renderer> ();

		if (Input.GetKeyDown(KeyCode.R) && access == false) 
		{
			isMatNew = false;
		}

		if (access == true) 
		{
			isMatNew = true;
			if (zeroSlider == true) 
			{
				isMatNew = false;
			}
		} 

		if (Input.GetKeyUp (KeyCode.R) && access == true) 
		{
			isMatNew = false;
		}

		if (isMatNew == true) 
		{
			t = 0.75f * Time.time;
			thres = Mathf.PingPong(t, max)+ 0.2f;

			newMat.SetFloat ("_Threshold", thres);

			foreach (Renderer rend in childrens) {
				var mats = new Material[rend.materials.Length];
				for (var j = 0; j < rend.materials.Length; j++) {
					mats [j] = newMat;
				}
				rend.materials = mats;
			}
		}
		if (isMatNew == false) 
		{
			foreach (Renderer rend in childrens) {
				var mainMats = new Material[rend.materials.Length];
				for (var k = 0; k < rend.materials.Length; k++) {
					mainMats [k] = mainMat;
				}
				rend.materials = mainMats;
			}
		}
	}
}

@Rembo4Fight
You are calling GetComponentsInChildren. It is a very slow method comparing to GetComponent. And you are using it in Update.

If the Renderers in the child objects do not alter in your app logic, you can set them to a Renderer collection field in Awake() method so that it will generate garbage only once. Then you can use them in update.

private List<Renderer> rendererList;

private void Awake()
{
         GetComponentsInChildrend(rendererList);
}

private void Update()
{
         UpdateRenderers(rendererList);
}

private void UpdateRenderers(List<Renderer> list)
{
         //Do stuff with renderers.
}

If the child objects are dynamic and can change, then let the child objects subscribe to this.
Use the GetComponentInChildren at last resort.