seefood_diet / Assets / UIKit / UIColorPaletteController.cs
UIColorPaletteController.cs
Raw
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UIKit {

    public interface IUIColorPaletteController {

        void Reload ();

        void RegisterListener (IUIColorObserver observer);
        void UnregisterListener (IUIColorObserver observer);

        UIColor GetColor (UIColorId id);
        void AddColor (UIColorId id, UIColor color);
    }

    [ExecuteInEditMode]
    public class UIColorPaletteController : IUIColorPaletteController {

        private static readonly UIColorPaletteController m_Instance = new UIColorPaletteController ();

        public static IUIColorPaletteController Default { get { return m_Instance; } }

        List<IUIColorObserver> m_Listeners = new List<IUIColorObserver> ();

        static UIColorPaletteController () { }

        protected UIColorPaletteController () {

            Reload ();
        }

        UIColorPalette m_DefaultAsset;

        public Dictionary<string, UIColor> ColorPalette = new Dictionary<string, UIColor> ();

        public void Reload () {

            ColorPalette.Clear ();
            LoadAsset ();
        }

        async void LoadAsset (Action completion = null) {

            var address = "UILibrary/ui-color_palette-default.asset";

            m_DefaultAsset = await AssetHelper.LoadAssetAsync<UIColorPalette> (address);

            foreach (var color in m_DefaultAsset.ColorPalette) {

                if (!ColorPalette.ContainsKey (color.Key)) {

                    ColorPalette.Add (color.Key, color.Value);
                }
            }

            NotifyAssetChanged ();
        }

        public UIColor GetColor (UIColorId id) {

            if (ColorPalette.Count == 0) {

                Reload ();
            }

            var key = id.ToString ();
            if (ColorPalette.ContainsKey (key)) {

                return ColorPalette[key];
            } else {

                return UIColor.Create ();
            }
        }

        public void AddColor (UIColorId id, UIColor color) {

            if (m_DefaultAsset == null) {

                return;
            }

            Debug.Log ("[UIKit] color palette: " + id.ToString () + " updated.");

            var key = id.ToString ();
            if (!m_DefaultAsset.ColorPalette.ContainsKey (key)) {
                m_DefaultAsset.ColorPalette.Add (key, new UIColor ());
            }

            m_DefaultAsset.ColorPalette[key] = color;
        }

        public void RegisterListener (IUIColorObserver observer) {

            m_Listeners.Add (observer);
        }

        public void UnregisterListener (IUIColorObserver observer) {

            m_Listeners.Remove (observer);
        }

        public void NotifyAssetChanged () {

            foreach (var listener in m_Listeners) {

                listener.OnUIColorChanged ();
            }
        }
    }
}