using UnityEngine;

[RequireComponent(typeof(Renderer))]
public sealed class MaterialColorChanger : MonoBehaviour {

    [SerializeField]
    private Color color1 = Color.white;
    [SerializeField]
    private Color color2 = Color.white;
    [SerializeField]
    private Color color3 = Color.white;

    private Renderer _renderer;
    private Color prevColor1;
    private Color prevColor2;
    private Color prevColor3;

    void Awake(){
        _renderer = GetComponent<Renderer>();
#if UNITY_EDITOR
        if(_renderer.materials.Length <= 0){
            Debug.LogError(string.Format("{0} の Renderer の Materials が0なのでColor変更出来ません。", transform.GetPath()));
            UnityEditor.EditorApplication.isPlaying = false;
        }
#endif
        prevColor1 = _renderer.materials[0].color;
        if(_renderer.materials.Length >= 2){
            prevColor2 = _renderer.materials[1].color;
        }else{
            prevColor2 = color2;
        }
        if(_renderer.materials.Length >= 3){
            prevColor3 = _renderer.materials[2].color;
        }else{
            prevColor3 = color3;
        }
    }

    void LateUpdate(){
        if(color1 != prevColor1){
            _renderer.materials[0].color = color1;
            prevColor1 = color1;
        }
        if(color2 != prevColor2){
#if UNITY_EDITOR
            if(_renderer.materials.Length < 2){
                Debug.LogError(string.Format("{0} の Renderer の Materials が足りないのでColor2を変更出来ません。", transform.GetPath()));
                UnityEditor.EditorApplication.isPlaying = false;
            }
#endif
            _renderer.materials[1].color = color2;
            prevColor2 = color2;
        }
        if(color3 != prevColor3){
#if UNITY_EDITOR
            if(_renderer.materials.Length < 3){
                Debug.LogError(string.Format("{0} の Renderer の Materials が足りないのでColor3を変更出来ません。", transform.GetPath()));
                UnityEditor.EditorApplication.isPlaying = false;
            }
#endif
            _renderer.materials[2].color = color3;
            prevColor3 = color3;
        }
    }
}
