Unity5学習メモ - Textureを変更する

TextureクラスとResources.Load

テクスチャーの設定は、Rendererに設定されているMaterialインスタンスに用意されている。
テクスチャーイメージの設定は、「mainTexture」というプロパティとして用意されていて、テクスチャー情報が保管されている。

Resources.Loadによるロード

リソースデータ(ファイルとして用意されているデータ類)を扱うために、Unityには「Resources」というクラスが用意されている。
この中の「Load」というメソッドを使って、リソースを読み込みオブジェクトを生成することができる。

変数 = Resources.Load ( リソースのパス );

// 引数には、読み込むリソースのパスを示すString値を指定。
// 「Resources」フォルダにある「Abc」というリソースなら単純に"Abc"でOK。
// 「Resources」フォルダにある「mydata」フォルダがあるなら、"mydata/Abc"でOK。
// ロードされたオブジェクトは、UnityのObjectクラスのインスタンスになっている。
// 例えばTextureであれば、これをTextureクラスにキャストして利用する。

Texture 変数 = (Texture) Resources.Load (Abc);

テクスチャーを変更するスクリプト

public class myscript : MonoBehaviour {
	Texture texture1;
	Color color1;

	void Start () {
		GameObject.Find("GUI Text").GetComponent<GUIText>().text = "Texture sample";

		// Resources.LoadでGrassHillオブジェクトをインスタンスし、Texture型にキャスト
		texture1 = (Texture)Resources.Load ("Grass (Hill)");

		// 現在の色を取得
		color1 = GetComponent<Renderer>().material.color;
	}

	void Update () {
		transform.Rotate (1f, 1f, 0.1f);
		if (Input.GetKeyDown (KeyCode.Space)) {

		// テクスチャーを適用
			GetComponent<Renderer>().material.mainTexture = texture1;
		// 下地の色は白にしておく (そうしないと下地の色と乗算みたいになる)
			GetComponent<Renderer>().material.color = Color.white;
		}
		if (Input.GetKeyUp (KeyCode.Space)) {

		// テクスチャーを削除
			GetComponent<Renderer>().material.mainTexture = null;
		// 元の色に戻す
			GetComponent<Renderer>().material.color = color1;
		}
	}
}

テクスチャーのサイズを操作する

デフォルトで設定されるテクスチャーは、等倍のまま図形に貼り付けられていく。

<Material>.mainTextureScale = <Vector2>;

上記のような感じでサイズを設定できる。
ただしmainTextureScaleは、マテリアルに設定されているメインのテクスチャーに関するもの。
Materialには、その他にもテクスチャーが用いられており、メインテクスチャー以外のサイズを操作する場合、Materialにあるメソッドを利用する必要がある。

// テクスチャーサイズを得る
Vector2 変数 = <Material>.getTextureScale (プロパティ名);

// テクスチャーサイズを設定する
<Material>.setTextureScale (プロパティ名, <Vector2> );

テクスチャーサイズをリアルタイムに変えるスクリプト

public class myscript : MonoBehaviour {
	Texture texture1;
	Color color1;
	float size = 1.0f; // テクスチャーサイズの変数

	void Start () {
		GameObject.Find("GUI Text").GetComponent<GUIText>().text = "Texture sample";

		// Resources.LoadでGrassHillオブジェクトをインスタンスし、Texture型にキャスト
		texture1 = (Texture)Resources.Load ("Grass (Hill)");

		// 現在の色を取得
		color1 = GetComponent<Renderer>().material.color;

		// mainTextureにGrass Hillをセット
		GetComponent<Renderer>().material.mainTexture = texture1;

		// 下地の色を白にする
		GetComponent<Renderer>().material.color = Color.white;
	}

	void Update () {
		transform.Rotate (1f, 1f, 0.1f);
		if (Input.GetKey (KeyCode.LeftArrow)) {
			size += 0.01f;

			// materialのSetTextureScaleメソッドで、テクスチャーをリアルタイムに適用していく
			// x値とy値は、同じサイズでいいので、size変数を設定
			// _MainTexというのはメインテクスチャーのこと
			GetComponent<Renderer>().material.SetTextureScale ("_MainTex", new Vector2 (size, size));
		}
		if (Input.GetKey (KeyCode.RightArrow)) {
			size -= 0.01f;
			if (size < 0) {
				size = 0f;
			}
			GetComponent<Renderer>().material.SetTextureScale ("_MainTex", new Vector2 (size, size));
		}
	}
}