- Home /
How to change material without memory leaks?
Hey all.
After searching for an answer I have learned that materials are handled a little different way. So now I know that each time the material property is accessed there is a copy of it created and that's what causes the leak. I tried to cache material before changing it with no success.
This is the original code I used (without caching):
SpriteRenderer sr;
float flashDurationLeft;
void Awake()
{
sr = GetComponent<SpriteRenderer>();
}
void FixedUpdate()
{
if (flashDurationLeft > 0)
{
if (sprite.material != GameManager.instance.enemyHit_mat)
sprite.material = GameManager.instance.enemyHit_mat;
flashDurationLeft -= Time.deltaTime;
} else if (flashDurationLeft <= 0)
{
if (sprite.material != GameManager.instance.defaultSprite_mat)
sprite.material = GameManager.instance.defaultSprite_mat;
}
}
How would you solve this problem?
Answer by Geometrical · Dec 21, 2016 at 11:39 PM
It's simple, just use the SharedMaterial property as the Material property is instance specific.
sprite.sharedMaterial
Worked like a charm, many thanks. But I am now quite confused how it works.
@xpavelos it's very simple. If you want to modify the material on an object without actually effecting the material file in the Unity Asset Database (the project's asset folder), you'll use the $$anonymous$$aterial property since it's object instance specific (meaning that the material will be cloned before it's given to the user for the current instance of the object). You'd use the Shared$$anonymous$$aterial property if changes to the the actual material file was intended.
Your answer
![](https://koobas.hobune.stream/wayback/20220612103210im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
editor script memory leak 1 Answer
EXC_BAD_ACCESS (SIGABRT) from Unity::Material::CreateMaterial 0 Answers
Normal map not showing correctly on 2d sprite 0 Answers
webgl memory leak 1 Answer