Search Unity

Question Why material's texture saved change?

Discussion in 'General Discussion' started by Stormer2020, Oct 31, 2022.

  1. Stormer2020

    Stormer2020

    Joined:
    Sep 14, 2020
    Posts:
    92
    Hi~
    I'm using Unity2021.3.12f1.
    I found a issue.

    I was change the material's texture at runtime by code:

    Code (CSharp):
    1. Texture pic = await requestRes.LoadLocal<Texture>("uv4x4") as Texture;
    2.         if (pic)
    3.         {
    4.             cube.GetComponent<MeshRenderer>().sharedMaterial.mainTexture = pic;
    5.         }
    When I stop the game, the material's texture(Base Map) has saved.

    Why? Is a new feature? How can I fix this? I don't wanna anything saved after game running.

    Thanks~ :)

    20221031171003.png

    20221031171055.png

    20221031171147.png
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,925
    Not a new feature. If you change the values of anything that isn't a scene level object, those changes persist between play sessions. Unity only backs up and restores scenes during play mode.

    You probably want to Instantiate() your material before you modify it. Just remember to Destroy() it after.
     
    Stormer2020 and Antypodish like this.
  3. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,183
    You need to use
    material
    instead of
    sharedMaterial
    . When you modify
    material
    at runtime a copy of the original material is created and modified, but when you modify
    sharedMaterial
    the material asset is modified which like @spiney199 pointed out will not be restored back to its original state when you leave play mode.

    https://docs.unity3d.com/ScriptReference/Renderer-material.html
     
    Stormer2020, Antypodish and spiney199 like this.
  4. Stormer2020

    Stormer2020

    Joined:
    Sep 14, 2020
    Posts:
    92
    Thank you! It works~ :D
     
  5. Stormer2020

    Stormer2020

    Joined:
    Sep 14, 2020
    Posts:
    92
    I got it. Thank you!
     
  6. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,638
    Wanted to note that this only happens in the editor in play mode. When you make a build, a build can't modify the original asset, so the sharedMaterial will always revert back to its original state each time you run the build.
     
    Stormer2020 and neginfinity like this.