Updated SyncVar Hook doc

This commit is contained in:
Chris Langsenkamp 2019-07-19 20:00:49 -04:00
parent 9432b84555
commit 17b61b5e6f

View File

@ -23,25 +23,23 @@ public class PlayerController : NetworkBehaviour
} }
[SyncVar(hook = nameof(SetColor))] [SyncVar(hook = nameof(SetColor))]
public Color playerColor = Color.black; Color playerColor = Color.black;
// Unity makes a clone of the material when // Unity makes a clone of the Material every time GetComponent<Renderer>().material is used.
// GetComponent<Renderer>().material is used. // Cache it here and Destroy it in OnDestroy to prevent a memory leak.
// Cache it here and Destroy it in OnDestroy Material cachedMaterial;
// to prevent a memory leak.
Material materialClone;
void SetColor(Color color) void SetColor(Color color)
{ {
if (materialClone == null) if (cachedMaterial == null)
materialClone = GetComponent<Renderer>().material; cachedMaterial = GetComponent<Renderer>().material;
materialClone.color = color; cachedMaterial.color = color;
} }
private void OnDestroy() void OnDestroy()
{ {
Destroy(materialClone); Destroy(cachedMaterial);
} }
} }
``` ```