Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct here to familiarize yourself with the rules and how to post constructively.

  2. Unity 2022.1 is now available as the latest Tech release.
    Dismiss Notice
  3. Improve your project's performance with our new guide on profiling in Unity.
    Dismiss Notice

[Solved ]Assigning material always create new instance...

Discussion in 'Scripting' started by PROE_, Aug 25, 2019.

  1. PROE_

    PROE_

    Joined:
    Feb 20, 2016
    Posts:
    31
    Hello, I've got a weird problem with materials :/ So I'm instacing prefab and then I want to assign material which is stored in List in ScriptableObject but to prevent instacing new ones I thought storing material from one object in new List would prevent it from creating new instances but it doesn't work... Every single object have different material instance :(
    Maybe there is something I'm missing :/

    Code (CSharp):
    1. var mat = GameplayUIManager.FurnitureDataContainer.FurnitureList[f.ContainerID].MaterialOptions[f.FurnitureObjData.UsedMaterial];
    2. var MaterialInstances = BuildingManager.Instance.MatInstNames;
    3.  
    4. if (!MaterialInstances.Contains(mat.name))
    5. {
    6.     var r = f.GetRenderers();
    7.     for (int i = 0; i < r.Count; i++)
    8.     {
    9.         if (i == 0)
    10.         {
    11.             r[0].sharedMaterial = mat;
    12.             MaterialInstances.Add(mat.name);
    13.             Instance.MatInstaces.Add(r[0].sharedMaterial);
    14.  
    15.             mat = Instance.MatInstaces[MaterialInstances.FindIndex(x => x == mat.name)];
    16.         }
    17.         else
    18.             r[i].sharedMaterial = mat;
    19.     }
    20. }
    21. else
    22. {
    23.     mat = Instance.MatInstaces[MaterialInstances.FindIndex(x => x == mat.name)];
    24.  
    25.     var r = f.GetRenderers();
    26.     for (int i = 0; i < r.Count; i++)
    27.         r[i].sharedMaterial = mat;
    28. }
    29.  
     
    HyronXIII likes this.
  2. PROE_

    PROE_

    Joined:
    Feb 20, 2016
    Posts:
    31
    Problem solved.
    The problem was that in other script I used "material" instead of "sharedMaterial" which caused new instance to pop up
     
    HyronXIII likes this.
unityunity