元放送部員の雑記帳

管理者:殻栗ポルタ/でんきやさんの備忘録だったり、紹介記事だったり。

UnityC#備忘録-Materialのタイリングをリアルタイムできれいにする(実行環境:5.6.3f1)

移行記事です。

Yughues Free Metal Materialsを使っていると、C#でうまく制御ができないことがわかりした。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlockMaterial : MonoBehaviour {
    public Material material;
    Vector2 size;

	// Use this for initialization
	void Start () {
        material = gameObject.GetComponent<Renderer>().material; //マテリアルの取得

	}
	
	// Update is called once per frame
	void Update () {
        size = new Vector2(gameObject.transform.localScale.x, gameObject.transform.localScale.z); //オブジェクトの大きさを取得
        material.mainTextureScale = size; //タイリングをセット
	}
}

上のスクリプトだと法線マップのタイリングがうまくいかないようです。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlaneMaterial : MonoBehaviour {
    public Material material;
    Vector2 size;

	// Use this for initialization
	void Start () {
        material = gameObject.GetComponent<Renderer>().material; //マテリアルの取得

	}
	
	// Update is called once per frame
	void Update () {
        size = new Vector2(gameObject.transform.localScale.x, gameObject.transform.localScale.z); //オブジェクトの大きさを取得
        material.mainTextureScale = size; //タイリングをセット
        material.SetTextureScale("_BumpMap", size); //タイリングをセット②
    }
}

 という風に一行記述を増やす必要があります。
まあ、Yughues Free Metal Materialsに限らず使うところはあると思いますが。

今回のスクリプトでは再生中にサイズを変更しても適用されるので活用できますね!

一応、もっとしっかりしたアセットもあります。(MasterCube等)
ただ、設定が増えてめんどくさい人やUnityC#の初心者(自分含む)は今回の方法でしてもいいと思います。