Search Unity

Assigning SharedMaterial from ScriptableObject but getting Instance

Discussion in 'Scripting' started by crudeMe, Feb 27, 2019.

  1. crudeMe

    crudeMe

    Joined:
    Jul 8, 2015
    Posts:
    92
    Hi,
    I'm storing an array of material references somewhere deep in ScriptableObject (SO). When I click on any material in SO in editor, Unity points me to an actual material entity inside of a project. Hence, I assume material references are set correctly.

    When I'm trying to assign an array of material references from SO to a sharedmaterial array of a runtime generated mesh, I get material Instances instead.

    Hope you're following.

    I've tried these two ways of assigning materials:
    Code (CSharp):
    1. MeshRenderer mRenderer;
    2. ScriptableObjectClass so;
    3.  
    4. mRenderer.sharedMaterials = so.materialsArray;
    Code (CSharp):
    1. MeshRenderer mRenderer;
    2. ScriptableObjectClass so;
    3.  
    4. Material[] mats = new Material[so.materialsArray.Length];
    5.  
    6. for (int i = 0; i < mats.Length; i++)
    7. {
    8. mats[i] = Material.Instantiate<Material>(so.materialsArray[i]);
    9. }
    10.  
    11. mRenderer.sharedMaterials = mats;
    Both of them are giving me materials copies instead shared materials.

    TL;DR How do I properly assign a material stored in ScriptableObject to a mesh renderer as a shared material, but not as a instance of a material.

    Thanks.