Talking to other scripts
Give a script a public field of another script's type, fill it in the Inspector, and use it directly.
public class ScoreBoard : StageTimeBehaviour
{
public ScoreBank bank; // another script, set in the Inspector
public void AddPoint()
{
bank.total += 1; // read and write its fields
int now = bank.AddPoints(1); // call methods with parameters and a result
bank.Celebrate(); // call its events
}
}
Reading and writing by name
GetProgramVariable and SetProgramVariable read and write any field (private ones too) by name. Cast the result
to the field's type.
int count = (int)counter.GetProgramVariable("count");
bank.SetProgramVariable("lastSlot", 2); // the value must have the field's type: 2 for int, 2f for float
Rules
- Writing another script's
[Synced]field needs ownership of that object, just like your own fields. - A method with parameters or a result runs immediately and returns its result. It is not an event: buttons,
SendCustomEventand the network cannot call it. - A script cannot be called back while it is still running: if A calls B and B calls A, both scripts stop. Call your own methods directly, not through a reference to yourself.
- At most 8 scripts can be calling each other at once.
- If the other script has crashed, its fields read as 0 / null and writes and calls are ignored (with one warning).
- Do not give two callable methods the same name (no overloads).
See the ScoreBoard example for all of this in one place.