読者です 読者をやめる 読者になる 読者になる

Unityな日々(Unity Geek)

Unityで可視化アプリを開発するための試行錯誤の覚書

Materialの色を変える

Materialの色は、(renderer.)material.SetColor("_Color", Color)で変更する。

下の例は、materialをPublic変数として受け取り、指定したOn/Off時間で色を変えるもの

using UnityEngine;
using System.Collections;

public class FlashingLight : MonoBehaviour {
	public Material mat;
	public float durationOn = 1.0F; //sec for On
	public float durationOff= 1.0F; //sec for Off
	public bool isOff;	//Start from Off (or from On)
	
	private Color color;
	private Color colorOff;
	private Color colorOn;
	private float currentTime;
	private float nextTime;
		
	// Use this for initialization
	void Start () {
		currentTime = 0.0F;
		colorOff 	= new Color(0.5F,0.5F,0.5F,1.0F);
		colorOn 	= new Color(1.0F,1.0F,0.0F,1.0F);
		if(isOff){
			color = colorOff;
			nextTime = durationOff;
		}else{
			color = colorOn;
			nextTime = durationOn;
		}
		mat.SetColor("_Color", color);
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		if(Time.time > nextTime){
			if(isOff){
				color = colorOn;
				isOff = false;
				nextTime += durationOn;
			}else{
				color = colorOff;
				isOff = true;
				nextTime += durationOff;
			}
			mat.SetColor("_Color", color);
		}
		
	}
}