- Home /
Changing the color of a material during runtime (works in editor, not build)
So, I've got this scene for customizing the color of your player: .
The player is a prefab that is instantiated in the game scene when it runs, and the materials I am editing in this scene belong to the prefab.
.
When I try it out in the editor, it works perfectly. it saves all of the colors correctly when the game is played, but when I build the game, I try to edit the player, but as soon as I switch scenes to the game, the colors revert to what they originally were.
.
Here is my code:
.
public Renderer Player;
public int Index;
public Color ResetColor;
public Slider Red;
public Slider Green;
public Slider Blue;
public RawImage bg;
private Color color;
void Start(){
color = Player.sharedMaterials[Index].color;
Red.value = color.r;
Green.value = color.g;
Blue.value = color.b;
}
public void Reset(){
Red.value = ResetColor.r;
Green.value = ResetColor.g;
Blue.value = ResetColor.b;
color = ResetColor;
}
void Update(){
bg.color = color;
color.r = Red.value;
color.g = Green.value;
color.b = Blue.value;
Player.sharedMaterials[Index].color = color;
}
.
There is a ColorScript for every body part I am editing, and the public variables are set correctly. Player is the prefab, and I am using sharedMaterials
because of that. I just don't understand why it works in the editor but not in the build. Can somebody please help me?
Thanks...
Answer by PlanarBit · May 04, 2019 at 06:44 PM
The reason is that by modifying sharedMaterial you modify material asset itself. You can verify this by inspecting your material after exiting play mode.
This is non-intuitive and strange at first but has very useful applications.
To start with, here is a simple rule to remember:
When run in Editor: All asset changes are preserved.
When run built player: Assets are read-only.
Also, take a look at documentation.
Thank you for the answer, I understand my problem more clearly now.
So would the best solution be to create a new material every time you save your new color? Would that be too hard on the computer/load time? Is this even possible? Is there a different way to go about it that I'm not thinking of? Thank you very much for your help.
I dont see you attempting to save the material color to be preserved between game runs. Is that what you want to achieve?
I would not say they are read only - the runtime assets can indeed be written, they are just not preserved when you quit the application
Your answer
![](https://koobas.hobune.stream/wayback/20220612200657im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
how to change object material with mouse click ? 2 Answers
Multiple Cars not working 1 Answer
how Load Prefabs after build 0 Answers
C# Instantiate Prefab from Class That Does not Inherit from MonoBehavior 2 Answers