Hello guys, I really tried finding out what is wrong with my code, I know it’s about “arrays” and “var” that is making a lot of garbage collection.
Please help me resolve this.
I tried profiler and this is what it shows about MatSwitch script:
Here is the script itself:
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;
}
}
}
}