Search Unity

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

I do not want instanced materials but the original materials in asset...

Discussion in 'Scripting' started by WILEz1975, Mar 4, 2015.

  1. WILEz1975

    WILEz1975

    Joined:
    Mar 23, 2013
    Posts:
    368
    I made a script that copy all materials from a gameobject to another. It 'a script that runs in the editor to press a button.

    Code (csharp):
    1. TargetComponents[j].gameObject.transform.GetComponent<Renderer>().material=ComponentsToAdd[i].gameObject.transform.GetComponent<Renderer>().materials;
    Is a Unity 5 script, but would be the same in unity 4, it makes little difference, like:

    Code (csharp):
    1. TargetComponents[j].gameObject.transform.render.materials=ComponentsToAdd[i].gameObject.transform.render.materials;
    Works but the materials that I copied are not the same but are instances. I would like to know how to tell him not to create instances but use their original materials in my asset.

    Is possible?
     
  2. Deleted User

    Deleted User

    Guest

    I had a similar problem before Unity5 too, I used to create materials at runtime and then assigning it to various meshes and I got all instances. I solved this by storing the material reference in a pooling manager, then get the material from there. It seems that getting a material reference from another mesh create instances no matter what, so you may want to keep it somewhere else and reference from there.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Use sharedMaterials instead of materials.

    --Eric
     
  4. WILEz1975

    WILEz1975

    Joined:
    Mar 23, 2013
    Posts:
    368
    Yes, it is one of the first things I tried. Same result.

    But I solved in another way.
    I created a new static array where set the original materials.
    Then set it as target gameobject materials array.
    Work.
     
  5. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    You need to say "sharedMaterials = " on the left side AND "renderer.sharedMaterials" on the right side.
     
  6. WILEz1975

    WILEz1975

    Joined:
    Mar 23, 2013
    Posts:
    368
    Yep. But nothing changes. Always instaced materials without this declaration:
    Code (csharp):
    1. [SerializeField]
    2. static Materials [] MyArrayMaterials;
    .....
    and after set the materials:
    Code (csharp):
    1. MyArrayMaterials=ComponentsToAdd.gameObject.transform.GetComponent<Renderer>().sharedMaterials;
    2. TargetComponents[j].gameObject.transform.GetComponent<Renderer>().sharedMaterials=MyArrayMaterials;[code]
     
    Nanako likes this.