要在 script 換掉 shader,就用 Shader.Find():
someGameObject.GetComponent<Renderer>().material = new Material(Shader.Find("MyShader"));
但我之前遇過一個怪現象,在PC上測試時,上面的 code 可以跑,但編譯成 android 後不行。原來 Unity 有段話我沒注意到(http://docs.unity3d.com/ScriptReference/Shader.Find.html):
Note that a shader might be not included into the player build if nothing
references it! In that case, Shader.Find will work only in the editor,
and will result in pink "missing shader" materials in the player build.
Because of that, it is advisable to use shader references instead of
finding them by name. To make sure a shader is included into the game
build, do either of: 1) reference it from some of the materials used in
your scene, 2) add it under "Always Included Shaders" list in
ProjectSettings/Graphics or 3) put shader or something that references it
(e.g. a Material) into a "Resources" folder.
第一種比較直覺,在 scene 中有使用的話,就會自動納入 player build。但要是物件是透過 script 產生的,這方法行不通。
第二種是透過 Edit->Project Settings -> Graphics 加入:
第三種方法,先把要用的 shaders 放在 Resources 目錄(Assets\Resources),script 再去載入,
Shader myShader = Resources.Load ("MyShader") as Shader;
someGameObject.GetComponent<Renderer>().material = new Material(myShader);
沒有留言:
張貼留言