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?

It’s simple, just use the SharedMaterial property as the Material property is instance specific.

sprite.sharedMaterial