Change material.color in code and revert on Quit

Hi everyone,

I’m using something like this to change the color of several objects.

skinMat.color = color;

skinMat is a Material attached in the inspector. The problem is when I change the color in-game, it keeps it afterwards. I’ve tried a bunch of things and no matter what it always keeps the color I chose in-game. I’d like to have the material revert back to its original state when I stop the game in the editor. There MUST be a way to do this, in code or otherwise.

Thanks in advance,

Jason

2 Answers

2

You’re better off instantiating the material.

var mat : Material;
private var matInstance : Material;

function Start () {
	matInstance = Instantiate(mat);
	renderer.material = matInstance;
	matInstance.color = Color.blue;
}

That way the original material is never touched, so if something ever goes wrong and OnApplicationQuit is never called (e.g. you accidentally write an infinite loop and have to force-quit, a crash, whatever), it’s not a problem.

yeah this is an ok way to do it, the issue with this is that you only change the material on 1 gameobject. dave's solution works better for me because any gameobject with that material will show changes. I dont think theres a way to achieve this your way, without looping through everything or using tags. thats not worth the trouble.

@JasonM: no, if you just assign the instantiated material to all GameObjects that should have it, then changing the instantiated material will change it on all of those GameObjects.

@Eric5h5 That would work, but my goal here is to avoid tracking all those gameobjects at all, theres too many. you have to assign the instantiated material at runtime, so gathering up those gameobjects would be quite a chore.

You could save it off on Start and restore it in OnApplicationQuit http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnApplicationQuit.html

Thanks, I asked a coworker 10sec after posting, he told me the same thing. exactly what I was looking for! thanks!