0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Unity】スクリプトからオブジェクトのマテリアル数を増やす方法

Posted at

前置き

image.png
1と2のマテリアルを融合させて3にしたい。

image.png
インスペクタからならMaterials項目を増やせば対応できるが
コードから動的に増減させたい。

結論

    public void Add(Material newMaterial)
    {
        // Rendererからマテリアルの配列を取得
        List<Material> materials = new List<Material>(GetComponent<Renderer>().materials);

        // 普通にマテリアルを追加
        materials.Add(newMaterial);

        // 上書き
        GetComponent<Renderer>().materials = materials.ToArray();
    }

materialsは固定長の配列型なのでListに変換してから増やす。
Listで管理してるだけなので、減らしたり順番を変えたりも簡単にできる。

おまけ

置き換えるだけならば以下。

    public void Replace(int index, Material newMaterial)
    {
        // ↓エラーにはならないが、動作しない↓
        // GetComponent<Renderer>().materials[index] = newMaterial;

        //配列を取得
        var materials = GetComponent<Renderer>().materials;

        //置き換える
        materials[index] = newMaterial;

        //上書き
        GetComponent<Renderer>().materials = materials;
    }
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?