85 lines
2.5 KiB
C#
85 lines
2.5 KiB
C#
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
public class MaterialAlphaHub : MonoBehaviour
|
||
{
|
||
// 注:Unity不支持运行时获得全部属性名称,因此需要编辑器脚本来初始化这个列表
|
||
public RendererAlphaData[] rendererAlphaDatas;
|
||
|
||
public float alphaRatio = 1f;
|
||
private float _lastAlphaRatio;
|
||
|
||
private void Awake()
|
||
{
|
||
_lastAlphaRatio = alphaRatio;
|
||
}
|
||
|
||
private void Start()
|
||
{
|
||
SetCurrentRatio();
|
||
}
|
||
|
||
private void LateUpdate()
|
||
{
|
||
if (_lastAlphaRatio != alphaRatio)
|
||
{
|
||
_lastAlphaRatio = alphaRatio;
|
||
SetCurrentRatio();
|
||
}
|
||
}
|
||
|
||
private void SetCurrentRatio()
|
||
{
|
||
for (var i = 0; i < rendererAlphaDatas.Length; i++)
|
||
rendererAlphaDatas[i].SetMaterialAlpha(alphaRatio);
|
||
}
|
||
|
||
[System.Serializable]
|
||
// 注:这个类实例仅能使用编辑器代码构造
|
||
public class RendererAlphaData
|
||
{
|
||
public Renderer renderer;
|
||
public MaterialAlphaData[] materialDatas;
|
||
|
||
public void SetMaterialAlpha(float ratio)
|
||
{
|
||
// 注:以materialDatas记录数量为准,实际翅膀会额外添加XRay材质
|
||
for (var i = 0; i < materialDatas.Length; i++)
|
||
materialDatas[i].SetMaterialAlpha(renderer.materials[i], ratio);
|
||
}
|
||
}
|
||
// 注:这个类实例仅能使用编辑器代码构造
|
||
[System.Serializable]
|
||
public class MaterialAlphaData
|
||
{
|
||
public List<PropertyAlphaData> parameterList = new List<PropertyAlphaData>();
|
||
|
||
public void SetMaterialAlpha(Material material, float ratio)
|
||
{
|
||
for (var i = 0; i < parameterList.Count; i++)
|
||
{
|
||
// 注:考虑到实际操作中,可能有颜色变化问题,因此每一帧都重新取得RGB值
|
||
var color = material.GetColor(parameterList[i].NameId);
|
||
color.a = parameterList[i].alpha * ratio;
|
||
material.SetColor(parameterList[i].NameId, color);
|
||
}
|
||
}
|
||
}
|
||
// 注:Unity不支持泛型序列化,因此不能使用KeyValue和MyTuple
|
||
[System.Serializable]
|
||
public struct PropertyAlphaData
|
||
{
|
||
public int NameId
|
||
{
|
||
get
|
||
{
|
||
if (_nameId == null)
|
||
_nameId = Shader.PropertyToID(name);
|
||
return _nameId.Value;
|
||
}
|
||
}
|
||
private int? _nameId;
|
||
public string name;
|
||
public float alpha;
|
||
}
|
||
} |