Files
Convention-Unity-Demo/Assets/Scripts/Environment/SkyUpdatement.cs

88 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using Convention;
using UnityEngine;
namespace Demo.Game
{
public class SkyUpdatement : Updatement<int>, IAssetBundleLoader
{
public static SkyUpdatement Make()
{
return new GameObject().AddComponent<SkyUpdatement>();
}
private readonly Dictionary<string, int> NameCache = new();
private readonly Dictionary<int, Material> MaterialCache = new();
public string SkyAssetBundlePath;
public AssetBundle SkyAssetBundle;
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(SkyAssetBundlePath))
return;
if (Cache < 0)
return;
if (Cache != data)
{
RenderSettings.skybox = MaterialCache[data];
Cache = data;
}
}
public override IEnumerator UnloadScript()
{
Cache = -1;
if (string.IsNullOrEmpty(SkyAssetBundlePath) == false)
yield return this.UnloadAssetBundle(SkyAssetBundlePath);
SkyAssetBundlePath = "";
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 =>
{
SkyAssetBundlePath = ab;
SkyAssetBundle = x;
});
}
/// <summary>
/// 在指定时刻切换天空
/// </summary>
/// <param name="time"></param>
/// <param name="sky"></param>
[Convention.RScript.Variable.Attr.Method]
public IEnumerator Add(float time, string sky)
{
var ir = SkyAssetBundle.LoadAssetAsync<Material>(sky);
ir.completed += delegate
{
var mat = ir.asset as Material;
if (NameCache.TryGetValue(sky, out int id) == false)
{
id = NameCache.Count;
NameCache[sky] = id;
}
MaterialCache[id] = mat;
ManualAddEntry(time, id, default);
};
yield return ir;
}
}
}