Files
Convention-Unity-Demo/Assets/Scripts/Framework/DDT.cs
2025-12-12 15:19:10 +08:00

107 lines
3.1 KiB
C#

using Convention;
using Demo.Attr;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Rendering;
namespace Demo.Game
{
[Scriptable]
public class DDT : ScriptableObject
{
protected override bool IsSelfEnableUpdate => false;
public static DDT Make()
{
return new GameObject().AddComponent<DDT>();
}
public NativeArray<float> Datas = new(128, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
public int Count { get; private set; } = 0;
[Convention.RScript.Variable.Attr.Method]
public void Add(float value)
{
if (Count >= Datas.Length)
Datas.ResizeArray(Mathf.FloorToInt(Count * 1.5f));
Datas[Count] = value;
Count++;
}
[Convention.RScript.Variable.Attr.Method]
public void Add(int barSplitTimes, int barCount, int tickCount)
{
Add((barCount + tickCount / (float)barSplitTimes) * OneBarTime);
}
[Convention.RScript.Variable.Attr.Method]
public float At(int index)
{
if (index < 0)
index = Count + index;
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException($"{index} is out of [0, {Count})");
return Datas[index];
}
/// <summary>
/// »ñÈ¡Êý¾Ý³¤¶È
/// </summary>
/// <returns></returns>
[Convention.RScript.Variable.Attr.Method]
public int GetCount()
{
return Count;
}
private void OnDestroy()
{
if (Datas.IsCreated)
Datas.Dispose();
}
#region Serialize
protected override bool IsImptSerialize => true;
protected override IEnumerator CreateAndLoadingImptCacheFile(ToolFile scriptFile, ToolFile cacheFile)
{
yield return this.ParseScript2Expr(scriptFile.LoadAsText());
using var stream = File.OpenWrite(cacheFile.GetFullPath());
using var writer = new BinaryWriter(stream);
writer.Write(Count);
for (int i = 0; i < Count; i++)
{
writer.Write(Datas[i]);
}
}
protected override IEnumerator LoadFromImptCacheFile(ToolFile cacheFile)
{
using var stream = File.OpenRead(cacheFile.GetFullPath());
using var reader = new BinaryReader(stream);
Count = reader.ReadInt32();
Datas.ResizeArray(Mathf.Max(128, Count));
for (int i = 0; i < Count; i++)
{
Datas[i] = reader.ReadSingle();
}
yield break;
}
#endregion
#if UNITY_EDITOR
[Setting, SerializeField] private List<float> d_Datas = new();
protected override IEnumerator DoSomethingDuringApplyScript()
{
yield return base.DoSomethingDuringApplyScript();
for (int i = 0; i < Count; i++)
d_Datas.Add(Datas[i]);
}
#endif
}
}