Cou氏の徒然日記

ほのぼの日記ブログです。

Unityで遊ぼう [ブロック崩し編 その6:ブロックの色を変えてみる]

前回の続き。 

coublood.hatenablog.com

 

ブロックの色も、最初はMaterialでつけていたんですが・・・

f:id:coublood:20210120000257p:plain

ずっと買えないものであれば、特に問題はないんですが、色々なパターンを作りたい場合は、その分、Materialを作成・設定して、それをGameObjectに反映しないといけないので面倒です。

なので、スクリプト上で変えた方が楽そうです。

 

色を変えるには、materialの設定を変えないといけないわけですが、

そのmaterialを変数に持っているのは、Rendererクラス

UnityEngine.Renderer - Unity スクリプトリファレンス (unity3d.com)

f:id:coublood:20210120001853p:plain

f:id:coublood:20210120001903p:plain

なので、Rendererを取得して、そのmaterial.colorに色を設定すればよさそうです。

取得はGetComponent関数でいけますので・・・

Component-GetComponent - Unity スクリプトリファレンス (unity3d.com)

f:id:coublood:20210120001303p:plain

 Block.csを修正。

start関数で色を設定するようにしてしまえばよさそうです。

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

public class Block : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // オブジェクトを初期化される際に、色を設定 //
        gameObject.GetComponent<Renderer>().material.color = new Color(0.0f, 0.6f, 0.8f, 0.3f);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnCollisionEnter(Collision collision)
    {
        // Rigidbody(今回の場合はBall)との衝突を検知したらオブジェクトを破棄する //
        Destroy(this.gameObject);   
    }
}

 

 試しに起動してみると、色もばっちり設定されていそうです。

f:id:coublood:20210120002849p:plain