predictServerState
predictServerState writes a value into the client’s copy of a game variable
so the screen can move immediately, rather than after a round trip to the
server.
predictServerState(ref: VarpRef | VarbitRef, value: Int): voidReference
Section titled “Reference”predictServerState(ref, value)
Section titled “predictServerState(ref, value)” <layer w="fill" h={24} onClick={() => { predictServerState(Varbits.STAMINA_ACTIVE, 1 - stamina); }}>Parameters
Section titled “Parameters”ref: AVarps.*orVarbits.*reference from a generated dictionary.value: AnInt. What the client’s copy becomes.
Returns
Section titled “Returns”Nothing.
Caveats
Section titled “Caveats”- It does not reach the server. Nothing is saved and no game logic runs.
The action still has to reach the server some other way — through an
optionsentry, which is what the server listens for. - The next server update replaces it. If the server disagrees, the server wins, and the screen corrects itself.
- Everything that reads the variable follows the prediction, including
components in other interfaces that are open. A
useDerivedresult that depends on it follows too. - A
useWatchon the variable does not fire for the prediction; it fires when the server’s update arrives. - It is for a game variable — a varp or a varbit. Not a skill.
- For a value that is genuinely yours rather than the game’s, use
useState.
Making a toggle feel instant
Section titled “Making a toggle feel instant”export const PredictButton = (): Component => { const stamina = useServerState(Varbits.STAMINA_ACTIVE);
return ( <layer w="fill" h={24} onClick={() => { predictServerState(Varbits.STAMINA_ACTIVE, 1 - stamina); }}> <StoneButton> <text w="fill" h="fill" text="Toggle stamina" font={Fonts.PLAIN} align="center" valign="middle" shadow color={Colors.AMBER} /> </StoneButton> </layer> );};In a real interface the same component would also carry an options entry,
which is what the server acts on.
Troubleshooting
Section titled “Troubleshooting”The value snaps back a moment later
Section titled “The value snaps back a moment later”The action usually never reached the server. Check there is an options entry,
and that the server handles it.
Nothing on screen changed
Section titled “Nothing on screen changed”Only components that read the variable follow it.
I only want to store something
Section titled “I only want to store something”Use useState.