• Unity
  • Why does all the SkeletonRenderer share one material instanc

  • Изменено
Related Discussions
...

I noticed that all the SkeletonRenderer instance sharing a single material instance from 'rendererObject'.
Why not instansiate a clone for each SkeletonRenderer object?
In this situation I cant control material parameters individually to each spine animation object.(I wrote a custom shader)

I made some modification to the source code and achieved my purpose, but I cannot be sure if it is fine to do like this.
If my modification crashed something please tell me.

// SkeletonRenderer.cs

public class SkeletonRenderer : MonoBehaviour {

//... Code

private Dictionary<Material, Material> _materialInstances = new Dictionary<Material, Material>();

//... Code

public virtual void OnDestroy () {

    //... Code

    foreach (var keyValuePair in _materialInstances)
    {
        if (Application.isPlaying)
            Destroy(keyValuePair.Value);
        else
            DestroyImmediate(keyValuePair.Value);
    }
    _materialInstances.Clear();
}

//... Code

public virtual void LateUpdate () {

    //... Code


#if !SPINE_TK2D
         Material material = (Material)((AtlasRegion)rendererObject).page.rendererObject;
#else
         Material material = (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject;
#endif

        {
            var keyMaterial = material;
            if (_materialInstances.ContainsKey(keyMaterial))
            {
                material = _materialInstances[keyMaterial];
            }
            else
            {
                material = Instantiate(material);
                material.hideFlags = HideFlags.DontSave;
                _materialInstances[keyMaterial] = material;
            }
        }

        //... Code
}
}

Material changes break dynamic batching. Eg, if you draw X of the same skeleton, it would be 1 draw call with the same material and X draw calls if they each had their own material.

Thank you, then I will add a method and spawn those instances manually.