89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using Convention;
|
||
using Demo.Attr;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
using UnityEngine.Rendering.LookDev;
|
||
|
||
namespace Demo.Game
|
||
{
|
||
[Scriptable]
|
||
public class MaterialUpdatement : Updatement<int>, IAssetBundleLoader
|
||
{
|
||
public static MaterialUpdatement Make()
|
||
{
|
||
return new GameObject().AddComponent<MaterialUpdatement>();
|
||
}
|
||
|
||
private readonly Dictionary<string, int> NameCache = new();
|
||
private readonly Dictionary<int, Material> MaterialCache = new();
|
||
|
||
public string MaterialAssetBundlePath = null;
|
||
public AssetBundle MaterialAssetBundle = null;
|
||
|
||
protected override int Lerp(int begin, int end, float t)
|
||
{
|
||
return begin;
|
||
}
|
||
|
||
[Content, SerializeField] private int Cache;
|
||
|
||
protected override void UpdateData(int data)
|
||
{
|
||
if (string.IsNullOrEmpty(MaterialAssetBundlePath))
|
||
return;
|
||
if (Cache < 0)
|
||
return;
|
||
if (Cache != data && Parent.TryGetComponent<MeshRenderer>(out var meshRenderer))
|
||
{
|
||
meshRenderer.material = MaterialCache[data];
|
||
Cache = data;
|
||
}
|
||
}
|
||
|
||
public override IEnumerator UnloadScript()
|
||
{
|
||
Cache = -1;
|
||
if (string.IsNullOrEmpty(MaterialAssetBundlePath) == false)
|
||
yield return this.UnloadAssetBundle(MaterialAssetBundlePath);
|
||
MaterialAssetBundlePath = null;
|
||
yield return base.UnloadScript();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 对应ab包名称,自动匹配对应平台
|
||
/// </summary>
|
||
/// <param name="ab"></param>
|
||
[Convention.RScript.Variable.Attr.Method]
|
||
public IEnumerator Load(string ab)
|
||
{
|
||
yield return this.LoadAssetBundle(ab, x =>
|
||
{
|
||
MaterialAssetBundlePath = ab;
|
||
MaterialAssetBundle = x;
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// 在指定时刻切换父物体上的MeshRenderer.material
|
||
/// </summary>
|
||
[Convention.RScript.Variable.Attr.Method]
|
||
public IEnumerator Add(float time, string material)
|
||
{
|
||
var ir = MaterialAssetBundle.LoadAssetAsync<Material>(material);
|
||
ir.completed += x =>
|
||
{
|
||
var mat = ir.asset as Material;
|
||
if (NameCache.TryGetValue(material, out int id) == false)
|
||
{
|
||
id = NameCache.Count;
|
||
NameCache[material] = id;
|
||
}
|
||
MaterialCache[id] = mat;
|
||
ManualAddEntry(time, id, default);
|
||
};
|
||
yield return ir;
|
||
}
|
||
}
|
||
}
|