RobotFactoryIncrementalGame/Assets/Scripts/ResourceGenerator.cs

108 lines
2.4 KiB
C#

using System;
using Unity.VisualScripting;
using UnityEngine;
[RequireComponent(typeof(ResourceSource))]
public class ResourceGenerator : MonoBehaviour
{
public int Interval;
public int Power = 0;
private ResourceSource source;
private long lastTime;
[ContextMenu("Clear Last Generation Time")]
public void ResetTime()
{
source = GetComponent<ResourceSource>();
PlayerPrefs.DeleteKey(GetLastTimePrefName());
PlayerPrefs.Save();
}
private void Start()
{
source = GetComponent<ResourceSource>();
// PlayerPrefs.DeleteKey(GetLastTimePrefName());
// PlayerPrefs.Save();
lastTime = long.Parse(
PlayerPrefs.GetString(GetLastTimePrefName(), GetCurrentTime().ToSafeString())
);
GenerateToNow(false);
}
private long GetCurrentTime()
{
return DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
}
private string GetPrefName(string suffix)
{
return $"ResourceGenerator_{source.Resource.Name}_{suffix}";
}
private string GetLastTimePrefName()
{
return GetPrefName("LastTime");
}
private void Update()
{
GenerateToNow(true);
PlayerPrefs.SetString(GetLastTimePrefName(), lastTime.ToSafeString());
}
private void GenerateToNow(bool online)
{
var now = GetCurrentTime();
GenerateToTime(now);
}
private void GenerateToTime(long time)
{
if (Interval == 0)
return;
var delta = time - lastTime;
if (delta > 1e8)
{
Debug.Log($"Too much time has passed: {time - lastTime}");
lastTime = time;
return;
}
// Debug.Log($"{time} - {lastTime} = {delta} since last generation");
long times = delta / Interval;
if (times > 0)
{
Generate((int)times);
lastTime += times * Interval;
}
}
private void Generate(int times)
{
// Debug.Log($"+{Power}x{times} {source.Resource.Name}");
ResourceStorage.Instance.AddResource(source.Resource, Power * times);
}
public float Progress
{
get
{
if (Interval == 0)
return 0;
var delta = GetCurrentTime() - lastTime;
return Math.Clamp(delta * 1.0f / Interval, 0, 1);
}
}
}