Search Unity

Changing material with persistence from within a build

Discussion in 'Scripting' started by Rogalog, Feb 23, 2017.

  1. Rogalog

    Rogalog

    Joined:
    Jun 18, 2016
    Posts:
    23
    Hi guys,

    I'm struggling on how to change the main texture of a material from within a build of my game and for it to persist through scene changes AND restarting the application.

    I'm trying to use a very basic CMS, where instead of using different materials and swapping the materials out on all the objects that require it, I just swap the main texture on one material that is being used by all the necessary objects throughout my game. This works fine while running through the editor but once in a build it fails to persist.

    I've read around and from what I can gather it's not possible, but there wasn't /a lot/ of information regarding it so I just wanted to make sure.

    I have a reference to the textures and the materials and set it using material.mainTexture = someOtherTexture.

    TL; DR: Is it possible to change a materials' main texture during runtime (in a build, not in the editor) and have it persist?

    Thank you :)
     
  2. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    You could setup an array of materials that it could possibly have.
    Then in the Awake function of this object user PlayerPrefs to get an index into this material array and set it.
    Everytime you change the material update the PlayerPrefs index.
    Note: You'll need to check if that PlayerPrefs key exists since it won't first time on launch and set it to the default index.
     
  3. Rogalog

    Rogalog

    Joined:
    Jun 18, 2016
    Posts:
    23
    Thank you for your reply. I've already started on a custom config file using XML as I feel like I have more control over it but PlayerPrefs are an equally good option.

    For anyone else interested: by the looks of things it's not possible to make permanent changes to assets from within a build so your best bet is to use scripting to manipulate it. I've heard things about AssetBundles which can be a good way of managing your assets but I've not looked into those so I can't vouch for how relevant they are.

    Thanks anyway guys :)