Write prediction logic in a GhostBehaviour
Use the GhostBehaviour methods, time, and transform APIs correctly inside the prediction loop.
A GhostBehaviour is a MonoBehaviour with extra methods that run inside Netcode's prediction loop. Its standard Update still runs once per frame as usual. Two consequences follow: the loop can run your code several times for the same tick, and outside those methods the GameObject's transform isn't always the tick-accurate value, because of tick smoothing.
This page covers the prediction methods available to you, how to trigger visuals only once from prediction, how to separate client and server logic, how to access time, how to read the tick-accurate transform and past input, how to switch a ghost between predicted and interpolated, how to parent a ghost under another ghost, and the mistakes to avoid.
To replicate state from a GhostBehaviour, refer to Replicate state over the network.
Prediction methods
Override these methods to run logic at the correct point in the prediction loop.
| Method | When it runs |
|---|---|
PredictionGatherInput(PredictionGatherInputContext context) |
Once per frame on the owning client, before the prediction loop. |
PredictionUpdate(PredictionUpdateContext context) |
Once per server tick on the server, and for each replayed tick on predicting clients. |
PredictionPhysicsUpdate(PredictionPhysicsUpdateContext context) |
Once per server tick on the server, and for each replayed tick on predicting clients, at the predicted physics step. |
Gather player input in PredictionGatherInput rather than in Update or PredictionUpdate. It runs on the owning client only, immediately before prediction, which keeps latency between input and the input sent to the server as low as possible. It also runs after Netcode applies ownership changes and new spawns, so it reads the correct ownership state. Update runs before Netcode applies them, so it can read stale ownership. Prediction rewrites input values as it replays ticks, so it can overwrite input you gather elsewhere.
With Partial Tick Mode Selection set to Full Ticks Only (the default for new projects) or with forced input latency (ClientTickRate.ForcedInputLatencyTicks), Netcode writes the last captured input back into your GhostInput right before PredictionGatherInput, so input you capture anywhere else is overwritten.
For a complete example, refer to the character sample in the Assets/GameObjectSample/0_Basics/3_Character folder of the Netcode samples project. It gathers input in PredictionGatherInput and moves the character in PredictionUpdate.
These prediction methods don't run at the frame rate. The server runs them at ClientServerTickRate.SimulationTickRate, which defaults to 60 Hz, whereas Update runs at the rendering rate. For more information about the loop that drives these methods, refer to Prediction.
Each frame, Unity and Netcode call these methods in the following order:
FixedUpdateUpdatePredictionGatherInputPredictionPhysicsUpdatePredictionUpdateLateUpdate
By default, PredictionUpdate runs on full ticks only, so a predicted ghost doesn't move on frames between two ticks. For partial ticks and Full Tick Smoothing, refer to Full ticks only.
Netcode calls the prediction methods of different GhostBehaviour scripts in Script Execution Order, which you set with the [DefaultExecutionOrder] attribute or in Project Settings > Script Execution Order. For a complete example, refer to the prediction sample in the Assets/GameObjectSample/0_Basics/2_Prediction folder of the Netcode samples project.
Run code when the object spawns or despawns
Override OnGhostSpawn and OnGhostDespawn to run code when the object starts or stops being networked, on the server and on each client. By default, this is equivalent to running code in Awake, except with delayed spawning.
| Method | When it runs |
|---|---|
OnGhostSpawn() |
On the server, when you instantiate the object or call Spawn. On a client, when the object arrives or when predicting a spawn. |
OnGhostDespawn() |
On the server, when you destroy the object or call Despawn. On a client, when the object is removed by a server despawn message. |
The following example keeps a list of the spawned players, for example for a scoreboard:
public partial class TrackedPlayer : GhostBehaviour
{
public static readonly List<GhostObject> SpawnedPlayers = new ();
public override void OnGhostSpawn()
{
// this would work in Awake, but not in the case of delayed spawning
SpawnedPlayers.Add(this.Ghost);
}
public override void OnGhostDespawn()
{
SpawnedPlayers.Remove(this.Ghost);
}
}
The example stores a reference to each GhostObject instead of its GhostId. GhostId is the ghost's ID across the network. It's assigned before OnGhostSpawn runs, except for a client predicted spawn, which has no ID until the server confirms it. Reading GhostId before then throws an exception. To check whether the ID is assigned, read GhostInfo.ghostId, which is 0 until the server confirms the spawn.
OnGhostSpawn can run before your GhostBehaviour's Awake, so don't use fields that you set in Awake or Start.
Add networked scripts to child GameObjects
A GhostBehaviour doesn't need to be on the same GameObject as the GhostObject component. You can add it to any child GameObject of the prefab, including inactive ones. The script belongs to the nearest GhostObject component on its own GameObject or above it.
Netcode only replicates the transform of the GameObject that has the GhostObject component. A child's own transform isn't replicated.
Trigger visuals only once from prediction
Prediction replays the same tick many times as new snapshots arrive. PredictionUpdate therefore runs repeatedly for the same tick, and anything that accumulates or fires once needs a guard.
Check Netcode.Time.IsFirstTimeFullyPredictingTick before applying that kind of change:
public override void PredictionUpdate(PredictionUpdateContext context)
{
// Runs many times per tick during rollback, so guard the effect.
if (Netcode.Time.IsFirstTimeFullyPredictingTick)
m_MuzzleFlash.Play();
}
IsFirstTimeFullyPredictingTick is one of several flags on NetworkTime. Others let you act on the final replayed tick instead, which is useful when you want prediction to finish before you apply a result to something outside the ghost. For more information, refer to Rollback and replay.
The guard matters for anything Netcode shouldn't roll back for you. Replicated state doesn't need it: a GhostField you overwrite or accumulate each tick is rolled back and re-applied, so replaying a tick produces the same result. Effects outside a ghost's scope, such as spawning an object or playing a sound, do need it, because nothing rewinds them.
The same rule applies to Unity's physics messages, because Netcode steps predicted physics inside the prediction loop. For the guards that collision and trigger handling needs, refer to Use physics with predicted GhostObjects.
Separate client and server logic
A GhostBehaviour runs on the server and on clients, so logic that belongs to only one of them needs a guard. IsServer and IsClient are available on both the GhostBehaviour and its Ghost:
if (IsServer)
{
// Award the score. The server owns this decision.
}
Pick the guard that matches the question you're asking:
| Guard | Question it answers |
|---|---|
IsServer |
Is this instance running server logic? |
IsClient |
Is this instance running client logic? |
CanWriteState |
Can this instance write replicated state? True on the server and on predicting clients. |
Use CanWriteState to test whether you can write to a predicted value, and IsServer for decisions that belong to the server alone, such as spawning or awarding score. They aren't the same test: a predicting client has CanWriteState true but IsServer false.
Important
Branching on IsServer or IsClient inside PredictionUpdate makes the server and a predicting client run different code, which is a common cause of mispredictions that are hard to diagnose. Aim to keep PredictionUpdate identical on both, and put role-specific work in another method.
Note
On a host, IsServer and IsClient are both true, because the host is both the server and a client. An if (IsServer) ... else ... pair therefore takes the server branch on a host and never runs the client branch. Write the two cases as independent if statements so that a host runs both. Test your project as a host as well as a dedicated server.
Access time
Each prediction method receives context.TickedDeltaTime, the delta time for the tick it's simulating. Netcode adjusts this value for the tick being simulated on the server or replayed on a predicting client. It's the prediction replacement for Time.deltaTime. Use it instead of Netcode.DeltaTime for better performance.
The static Netcode class gives you the following time and tick rate values:
| Accessor | Value |
|---|---|
Netcode.Time |
The current NetworkTime. |
Netcode.DeltaTime |
The delta time of the current update, for code outside the prediction methods. |
Netcode.Tick |
The current tick on the server and the predicted tick on clients. |
Netcode.InterpolationTick |
The tick interpolated objects show. |
Netcode.ClientServerTickRate |
The server tick rate settings. |
Netcode.ClientTickRate |
The client interpolation and prediction settings. |
Important
Don't use Time.deltaTime or Time.fixedDeltaTime in a prediction method. They relate to the standard GameObject Update loop, which is separate from the prediction loop.
Sync time across clients
Time.time isn't synced. To get a time that evolves identically on all clients and that you can use for prediction, use Netcode.Tick. To get a time in seconds, divide by your simulation tick rate.
Read the simulation tick rate
You configure the tick rate on the NetcodeConfig asset. At runtime, read it from Netcode.ClientServerTickRate:
ClientServerTickRate tickRate = Netcode.ClientServerTickRate;
int ticksPerSecond = tickRate.SimulationTickRate;
float secondsPerTick = tickRate.SimulationFixedTimeStep;
Cache the result rather than querying every tick. The tick rate doesn't change during a session, so reading it once in Awake or Start is enough.
Read the tick-accurate transform
Unity renders the GameObject's transform, and Netcode smooths it for presentation in a few cases: while a ghost transitions between predicted and interpolated, on a host or client with Full Tick Smoothing when using full ticks only, and while prediction error correction runs. Outside the prediction loop, transform.position isn't necessarily the position the simulation uses.
For tick-accurate gameplay decisions, read transform.position from inside PredictionUpdate. To access the tick-accurate value outside prediction, read the transform from the GhostObject component instead:
// Non-smoothed, tick-accurate.
LocalTransform t = Ghost.GhostTransform.Read(); // use this to access all fields in one batch.
Vector3 authoritative = Ghost.Position; // for individual fields
Quaternion rotation = Ghost.Rotation;
// May be visually smoothed when outside PredictionUpdate.
Vector3 rendered = transform.localPosition;
Ghost.GhostTransform holds a reference to the underlying authoritative tick-accurate transform (the LocalTransform in entity component system (ECS) workflows). Ghost.Position and Ghost.Rotation provide shorthand access to read and write position and rotation on that LocalTransform. Ghost.PublishTransform() copies the tick-accurate transform onto the GameObject, in the same way a Rigidbody component publishes its pose.
Much like Rigidbody physics and FixedUpdate, transform.position is safe to use with physics inside PredictionPhysicsUpdate, and safe to use without physics inside PredictionUpdate.
To move a predicted ghost to a new position in a single step, such as respawning a player at a spawn point, change this.gameObject.transform inside PredictionUpdate, like any other movement. For the thresholds that decide whether the move snaps or glides on clients, refer to Snap large position changes.
Read past input
Inside the prediction loop it can be useful to refer to the previous tick's input data. Use the previous input to compute a delta, or to detect that a button was just pressed rather than held:
GhostInput<PlayerInput> input;
public override void PredictionUpdate(PredictionUpdateContext context)
{
if (input.TryGetCapturedAtPreviousTick(out PlayerInput previous))
{
// Compare against the current input to detect a change.
}
}
TryGetCapturedAtPreviousTick reads the input from the previous tick, accounting for the current simulation step batch size. TryGetCapturedAtTick reads a specific tick. Both return false when the buffer holds no input for that tick, which happens on the first ticks after a spawn.
For discrete actions such as jumping or firing, use an InputEvent field on your input struct so that you don't lose inputs triggered on frames between ticks.
Save on prediction performance with prediction switching
Prediction runs a full gameplay tick multiple times per frame. With thousands of ghosts, predicting every ghost adds significant CPU cost, most of which has no gameplay benefit. Predict only the ghosts the player interacts with, and switch the rest to interpolated mode dynamically. This creates a prediction bubble around the player.
The following example switches ghosts between predicted and interpolated mode based on their distance to the player:
// Predict this ghost, blending the visual transition over 0.2 s.
ghostObject.ConvertToPredicted(0.2f);
// Go back to interpolated.
ghostObject.ConvertToInterpolated(0.2f);
Typical games have fewer than a few dozen predicted ghosts at once, with everything else interpolated.
A ghost can only change mode if Enable Prediction is enabled and Predict is set to On Demand. Start as then sets the mode the ghost spawns in. Ghosts set to Only on Owner switch automatically when the owner changes. The new owner predicts the ghost and every other client interpolates it, so you can't switch these ghosts manually.
To check whether a switch is possible before you request it, call Ghost.World.PredictionSwitching.CanSwitchToPredicted(Ghost) or CanSwitchToInterpolated(Ghost). They return false if the ghost is already in that mode or is still blending a previous transition.
A non-zero transition time smooths the visual change. Interpolated objects are in the past, because interpolation information takes time to arrive on the client from the server. Predicted objects are in the present for the client, and so they're in the future compared with the interpolated data arriving from the server. Prediction switching can therefore produce visual jitter, as the object jumps backwards and forwards in time.
When you configure a transition time, Netcode smooths between the two timelines. PredictionUpdate and PredictionPhysicsUpdate begin running immediately, and Netcode then manipulates the GameObject transform to smooth the visual jitter of moving between timelines. This is one of the cases where the transform and the GhostTransform disagree, so read the GhostTransform for accurate predicted gameplay during a transition. Ghost.World.PredictionSwitching.IsSmoothingModeChange(Ghost) returns true while a transition is still blending.
For a complete example, refer to the prediction switching sample in the Assets/GameObjectSample/0_Basics/5_PredictionSwitching folder of the Netcode samples project. It predicts the objects near the player and interpolates the rest.
For background on the trade-offs, refer to Prediction switching.
Parent a ghost under another ghost
By default, Netcode doesn't replicate the parent of a ghost. To replicate it, enable Parent Replication on the GhostObject component of the child ghost's prefab. Then change the parent with the standard Transform API. Clients apply the same parent.
A parent must be a spawned ghost. Netcode reverts an invalid parent automatically.
Parenting works with prediction, and Netcode rolls it back like any other state. The following example parents an item from PredictionUpdate based on player input, so the owning client predicts the change and the server confirms it:
public struct CarryInput : IInputComponentData
{
public InputEvent Grab;
public InputEvent Drop;
}
public partial class Carrier : GhostBehaviour
{
[SerializeField] GhostObject m_Item;
GhostInput<CarryInput> m_Input;
public override void PredictionUpdate(PredictionUpdateContext context)
{
CarryInput input = m_Input.GetForCurrentTick();
if (input.Grab.IsSet)
m_Item.transform.SetParent(Ghost.transform);
if (input.Drop.IsSet)
m_Item.transform.SetParent(null);
}
}
A client can only change the parent of a ghost that it predicts. On an interpolated ghost, Netcode reverts the change and logs an error. The server overrides any parent change a client makes.
React to parent changes
To know when the parent changes, subscribe to OnParentChanged on the GhostObject component. It passes the previous parent and the new parent. null means the root. A predicted ghost replays its parent changes, so to trigger visuals only once, check Netcode.Time.IsFirstTimeFullyPredictingTick. An interpolated ghost receives each replicated parent change once, outside the prediction loop, where that flag is always false, so skip the check for interpolated ghosts:
public partial class CarryEffect : GhostBehaviour
{
[SerializeField] ParticleSystem m_PickUpEffect;
public override void Awake()
{
base.Awake();
Ghost.OnParentChanged += HandleParentChanged;
}
void HandleParentChanged(Transform previousParent, Transform newParent)
{
// A predicted ghost replays its parent change, so play the effect only the first time.
// An interpolated ghost receives each replicated parent change once, outside the prediction loop.
bool isFirstTime = !CanWriteState || Netcode.Time.IsFirstTimeFullyPredictingTick;
if (newParent != null && isFirstTime)
m_PickUpEffect.Play();
}
}
Avoid these mistakes
Declare every networked script as partial
Netcode generates the other half of your class, so declare every GhostBehaviour subclass partial.
Call the base Awake and OnDestroy methods
If you override Awake or OnDestroy, call the base method. GhostBehaviour.Awake links the script to its ghost and OnDestroy unlinks it. Without base.Awake, Unity Netcode can tear down the ghost while the script still uses it, and without base.OnDestroy, the ghost stays alive after its GameObject is destroyed.
The following example calls base.Awake and base.OnDestroy from overridden methods:
public override void Awake()
{
base.Awake();
// Your setup.
}
Read Netcode state on the main thread
The static Netcode accessors and GhostField<T>.Value aren't job safe. Read the values you need on the main thread and pass them into the job.
Add only one script of each type to a ghost
Two GhostBehaviour scripts on the same ghost must not be the same type, and one must not inherit from the other. Their GhostField values map onto the same underlying ECS component, so the two scripts share state. Netcode logs an error in the Editor and in development builds when it detects this.