using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;

[CustomEditor(typeof(WorldSlider))]
public class WorldSliderEditor : Editor
{
    [MenuItem("WorldSlider", menuItem = "GameObject/2D Object/World Slider")]
    public static void CreateWorldSlider()
    {
        var asset = Resources.Load("Slider");
        var instance = Instantiate(asset) as GameObject;
        instance.name = asset.name;
        if (Selection.activeTransform)
        {
            instance.transform.SetParent(Selection.activeTransform);
            instance.transform.localPosition = Vector3.zero;
            instance.transform.localScale = Vector3.one;
        }
        Selection.activeGameObject = instance;
        EditorUtility.SetDirty(instance);
    }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        var slider = (WorldSlider)target;
        slider.value = Mathf.Clamp(slider.value, 0, 1);
        slider.background.GetComponent<SpriteRenderer>().color = slider.backgroundColor;
        slider.fill.GetComponent<SpriteRenderer>().color = slider.fillColor;
        slider.fill.localScale = new Vector3(slider.value, 1, 1);
    }
}
#endif

public class WorldSlider : MonoBehaviour
{
    [Range(0, 1)]
    public float value = 1;
    public Transform background;
    public Transform fill;

    public Color fillColor = Color.red;
    public Color backgroundColor = Color.black;

    private SpriteRenderer backRenderer;
    private SpriteRenderer fillRenderer;
    private void Start()
    {
        backRenderer = background.GetComponent<SpriteRenderer>();
        fillRenderer = fill.GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        value = Mathf.Clamp(value, 0, 1);
        fill.localScale = new Vector3(value, 1, 1);

        backRenderer.color = backgroundColor;
        fillRenderer.color = fillColor;
    }
}
