publicに設定したテクスチャと差し替える場合
以下の様なプログラムとなります。Cubeなどを作成して追加して下さい。
【JavaScriptプログラム】
var playerTexture1 : Texture; var playerTexture2 : Texture; function OnGUI () { GUILayout.BeginArea(Rect(5, 5, 100, Screen.height-10)); if (GUILayout.Button("Change")) { if (renderer.material.mainTexture == playerTexture1) { renderer.material.mainTexture = playerTexture2; } else { renderer.material.mainTexture = playerTexture1; } } GUILayout.EndArea(); }
- テクスチャを2つ準備し、 playerTexture1 、 playerTexture2 に設定して下さい。
- renderer.material.mainTexture にテクスチャを代入する事で変更出来ます。
Resourcesフォルダのファイルをロードして差し替える場合
他の方法ではAssetsフォルダ内にResourcesフォルダを作成し、そこに画像ファイルを置いておくとそこから読み込む事が可能です。
以下の様なプログラムとなります。先ほどのサンプルと同様にCubeなどを作成して追加して下さい。
【JavaScriptプログラム】
private var defulatTexture : Texture; function Start () { defulatTexture = renderer.material.mainTexture; } function OnGUI () { GUILayout.BeginArea(Rect(5, 5, 100, Screen.height-10)); if (GUILayout.Button("Change")) { if (renderer.material.mainTexture == defulatTexture) { renderer.material.mainTexture = Instantiate(Resources.Load("PlayerTexture2")); } else { renderer.material.mainTexture = defulatTexture; } } GUILayout.EndArea(); }
Instantiate(Resources.Load("PlayerTexture2")) でロードとインスタンスの生成を行っています。
テクスチャファイルの設定を一部変更しておかないと実行した時に以下の様なエラーが発生します。
Instantiating a non-readable 'PlayerTexture2' texture is not allowed! Please mark the texture readable in the inspector or don't instantiate it. UnityEngine.Object:Instantiate(Object)
テクスチャのInspectorの Texture Type を Advanced に切り替え、 Read/Write Enabled にチェックを付けるとこのエラーは発生しなくなります。