LoginSignup
12
7

More than 5 years have passed since last update.

UnityでRenderer毎にShaderPropertyを制御する

Last updated at Posted at 2016-01-18

目的

Materialを共有しているRendererにおいてUVスクロールやカラー値等のパラメータを個別に渡したい

手段1. Materialを複製する

手っ取り早くやるならこっち。
DynamicBatchingの恩恵は受けれない。
Renderer.materialは内部でキャッシュするか作り直すようなので複数回呼んでもメモリリークはしなかった。
(※MaterialをnewやInstantiateで作った場合は明示的にMaterialをDestroyしないとメモリリークしていた。)

using UnityEngine;


public class Test : MonoBehaviour {
    public Color color = Color.white;

    private Material mat = null;

    void Start() {
        Renderer renderer = this.GetComponent<Renderer>();
        this.mat = renderer.material;   // ※複製が必要ない場合はsharedMaterialから取得すればいい
    }

    void Update() {
        this.mat.SetColor("_Color", this.color);
    }
}

手段2. Materialを使いまわす

Material数が非常に多い場合はこちらの方がメモリの節約ができる。
またShaderPropertyのパラメータが全て一致している場合はDynamicBatching対象となっていた。
(※頂点シェーダーで頂点をいじっている場合はDynamicBatchingによってメッシュが崩れていた。)

using UnityEngine;


public class Test : MonoBehaviour {
    public Color color = Color.white;

    private MaterialPropertyBlock mpb = null;
    private Renderer ren = null;

    void Start() {
        this.mpb = new MaterialPropertyBlock();
        this.ren = this.GetComponent<Renderer>();
    }

    void Update() {
        this.mpb.SetColor("_Color", this.color);
        this.ren.SetPropertyBlock(this.mpb);
    }
}
12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7