Here’s how I would go about it.
First, you need a DateTime that represents the last time the stock on this character was updated.
DateTime lastRefresh = DateTime.Now;
You’ll also need an int representing the time between refreshes
[SerializeField] int hoursBetweenRefresh = 1;
Then, I’d add this to the SetShopper method. This is the best time to check for restocking.
public void SetShopper(Shopper shopper)
{
currentShopper = shopper;
int totalHours = (int)Math.Floor((DateTime.Now - lastRefresh).TotalHours);
if (totalHours > hoursBetweenRefresh)
{
int amountToRestock = totalHours / hoursBetweenRefresh;
foreach (InventoryItem item in stockSold.Keys.ToList())
{
stockSold[item] -= amountToRestock;
if (stockSold[item] <= 0) stockSold.Remove(item);
}
lastRefresh = DateTime.Now;
}
}
So here’s the logic:
Whenever we SetShopper, we check to see if the time has elapsed… I chose hours, but you could choose TotalMinutes if you prefer. If it has, then we go through each item in the Dictionary and reduce the amount sold by the number of hours / the time per refresh.
If the result is zero, then the entry is removed, effectively restocking that item completely.
To make this value save, we need to make a few small changes in the ISaveable as well:
public object CaptureState()
{
Dictionary<string, int> saveObject = new Dictionary<string, int>();
foreach (var pair in stockSold)
{
saveObject[pair.Key.GetItemID()] = pair.Value;
}
saveObject["LastRefresh"] = (int)Math.Floor((DateTime.Now - lastRefresh).TotalHours);
return saveObject;
}
public void RestoreState(object state)
{
Dictionary<string, int> saveObject = (Dictionary<string, int>) state;
stockSold.Clear();
foreach (var pair in saveObject)
{
if (pair.Key == "LastRefresh")
{
lastRefresh = DateTime.Now.AddHours(-pair.Value);
} else
{
stockSold[InventoryItem.GetFromID(pair.Key)] = pair.Value;
}
}
}