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


/// <summary>
/// 使带有多个材质球的物体变透明
/// </summary>
public class BaseWallControlTwo : MonoBehaviour
{
    /// <summary>
    /// 
    /// </summary>
    [Tooltip("")]
    public List<Collider> colliders = new List<Collider>();
    /// <summary>
    /// 
    /// </summary>
    [Tooltip("")]
    public List<string> MyTransparent = new List<string>();
    /// <summary>
    /// 
    /// </summary>
    [Tooltip("")]
    public bool ChildRenderer;

    private List<MeshRenderer> meshRenderers;
    private List<Material> materials;

    public List<Material> empty = new List<Material>();
    /// <summary>
    /// 透明材质
    /// </summary>
    [Tooltip("透明材质")]
    public Material TransparentMat;

    public List<MeshRenderer> MeshRenderers
    {
        get
        {
            if (meshRenderers == null)
                meshRenderers = GetComponentsInChildren<MeshRenderer>().ToList();
            return meshRenderers;
        }
    }

    public List<Material> Materials
    {
        get
        {
            if (materials == null)
            {
                materials = new List<Material>();
                MeshRenderers.ForEach(render =>
                {
                    Array.ForEach(render.materials, (_mat) =>
                    {
                        if (!materials.Contains(_mat))
                        {
                            materials.Add(_mat);
                            Material _emp = new Material(_mat);
                            empty.Add(_emp);
                        }
                    });
                });
            }
            return materials;
        }
    }
    void Start()
    {
        colliders = GetComponents<Collider>().ToList();

        for (int i = 0; i < Materials.Count; i++)
        {
            if (Materials[i].renderQueue == 3000)
            {
                MyTransparent.Add(Materials[i].name);
            }
        }

    }

    /// <summary>
    /// 透明显示
    /// </summary>
    [ContextMenu("透明显示")]
    public void OpaquesTwo()
    {
        MeshRenderers.ForEach(renderer =>
        {
            Array.ForEach(renderer.materials, mat =>
            {
                mat.CopyPropertiesFromMaterial(TransparentMat);
            });
        });
        //禁用碰撞
        colliders.ForEach(x => x.enabled = false);
    }
    /// <summary>
    /// 取消透明显示
    /// </summary>
    [ContextMenu("取消透明显示")]
    public void OpaquesTwoFalse()
    {
        MeshRenderers.ForEach(renderer =>
        {
            Array.ForEach(renderer.materials, mat =>
            {
                mat.CopyPropertiesFromMaterial(empty.Find(x => x.name.Equals(mat.name)));
            });
        });
        //启用碰撞
        colliders.ForEach(x => x.enabled = true);
    }
}
