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

public class SpotLightSetUp : MonoBehaviour {

    public string ShaderName = "Paco/PointLight/ColorDiffuse";
    private Light pointLight;

    private void Awake()
    {
        UpdateShaders();
    }


    private void UpdateShaders()
    {
        float xPos = transform.position.x;
        float yPos = transform.position.y;
        float zPos = transform.position.z;
        pointLight = GetComponent<Light>();
        foreach (Material mat in findAllMaterialsInRange(pointLight.range)) {
            if (mat != null && mat.shader != null && mat.shader.name != null && mat.shader.name == ShaderName) {
                mat.SetFloat("_LightX", xPos);
                mat.SetFloat("_LightY", yPos);
                mat.SetFloat("_LightZ", zPos);
            }



        }
    }

    private Material[] findAllMaterialsInRange(float range)
    {
        List<Material> retVal = new List<Material>();

        Renderer[] arrend = (Renderer[])FindObjectsOfType(typeof(Renderer));
        foreach (Renderer rend in arrend) {
            foreach (Material mat in rend.materials) {
                if (!retVal.Contains(mat) && Vector3.Distance(transform.position,rend.transform.position) <= range) {
                    retVal.Add(mat);
                }
            }
        }

        return retVal.ToArray();
    }

}
