14. Keep values between calls
Increase a count on each OnTick call, keeping its previous value. Then choose a value to retain after prestige. Persist unlocks with your first Recompile.
Store a value outside the method
Writing int count = 0; inside OnTick starts it at 0 on every call. Use a Program field to keep the value between calls.
public class Program : ArcaneProgram
{
private int count = 0;
public void OnTick()
{
count++;
if (count == 3)
{
Workshop.Log.Write("Third call.");
}
}
}count is declared outside OnTick. It becomes 1 on the first call, 2 on the next, and 3 on the third, when Third call. appears. On the fourth call it becomes 4, so the message does not appear.
The number of OnTick calls is not an exact count of elapsed seconds.
Retain a value after prestige
Ordinary fields reset on prestige. Add [Persist] before a supported Program field to retain its value after prestige.
For a mining target, write [Persist] private int oreTarget = 100;. Compare Total < oreTarget in OnTick to use it. Persist retains values. It does not grant resources or restore jobs from a previous run.
When handlers run
| Name | When it runs |
|---|---|
| OnStart | Initial start or normal resume in the same session |
| OnTick | Periodically while the script runs |
| OnRestored | Resume a saved executable after rejoining |
| OnPrestige | Notification after prestige |
Fields remain intact when you stop and normally resume in the same session. After rejoining, resume the script yourself. See Prestige and carryover for event ordering when prestige and resume coincide, and for which data survives.
Exercise
Which declaration would you change to keep count after prestige?
Show example solutionHide example solution
Change private int count = 0; directly inside Program to [Persist] private int count = 0;. Keep it outside OnTick. Persist applies to a Program field.
