- Home /
garbage collection: material
below is my code. i want to know if the material i created is collected at the beginning of the next update cycle.if not how could i collect it?
public Color objectColor;
private Material material;
void Update()
{
material = new Material(renderer.sharedMaterial);
material.color = objectColor;
renderer.sharedMaterial = material;
}
Answer by dsada · Sep 27, 2014 at 05:17 PM
They are not destroyed but you can do it manually like this:
public Color objectColor;
private Material material;
void Update()
{
Material tmpMat = renderer.sharedMaterial;
material = new Material(renderer.sharedMaterial);
material.color = objectColor;
renderer.sharedMaterial = material;
Destroy(tmpMat);
}
However let me ask you why do you create a new material? Is it really necessary? Instead of this code that we can see you can calmly wrtite something like this:
public Color objectColor;
void Update()
{
renderer.sharedMaterial.color = objectColor;
}
And another question: why do you need to assign the color every frame? Does it change? because if not, you can assign once and you've got even less problem:
public Color objectColor;
void Start()
{
renderer.sharedMaterial.color = objectColor;
}
yea thats what i was looking for as to your two questions when i use sharedmaterial it changes color for everything and i dont want that. also i wanted to see the color change(in editor mode)thats why its in update but later on it will be moved to start.
Answer by Eric5h5 · Sep 27, 2014 at 02:32 PM
It will never be garbage collected because it's in use. The point of garbage collection is that it removes objects that aren't being referenced by anything. But even if it wasn't being used, no Unity objects are garbage collected, only Mono objects are.
when material = new $$anonymous$$aterial(renderer.shared$$anonymous$$aterial);
a new material is created and assigned to the variable material. lets call the new material.. material A then at the next iteration a new material is created again lets call it material b so before material = material A but now its material = material b therefore material A is no longer in use thats why i thought it might be collected.
Your answer
![](https://koobas.hobune.stream/wayback/20220613163906im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Better way of Animating linear movement than AnimationCurve.Linear()? 1 Answer
how does houses in the nature deal with garbage and other kinds of waste 1 Answer
UnloadAssets / ReloadBehaviors In Profiler During Scene Change 0 Answers
Enabling Particle System's Emission Results Huge Amount Of GC 0 Answers