Files
nexus/wiki/concepts/NetworkVariable.md
2026-04-26 12:02:53 +08:00

1.5 KiB
Raw Blame History

title, type, tags, sources, last_updated
title type tags sources last_updated
NetworkVariable concept
networking
unity
ngo
unity-multiplayer-engineer
2026-04-26

Aliases

  • NetworkVariable
  • NV (abbreviation)

Definition

NetworkVariable<T> 是 Unity Netcode for GameObjectsNGO中的核心类型用于持久化复制状态——当值发生变化时自动通过网络同步到所有客户端。仅在值真正变化时触发同步dirty check

Usage Rules

场景 应使用
持久化、需要同步的状态 NetworkVariable
一次性事件、触发通知 ClientRpc / ServerRpc

核心原则:持久化用 NetworkVariable一次性事件用 RPC不可混用。

Bandwidth Considerations

  • 避免在 Update() 中重复设置相同值——触发无意义的网络同步
  • 对高频数值使用差分压缩(INetworkSerializable
  • 非关键状态(血条、分数)限流至最高 10Hz

Example

// 健康值:持久化 → NetworkVariable
public NetworkVariable<int> PlayerHealth = new(100,
    NetworkVariableReadPermission.Everyone,
    NetworkVariableWritePermission.Server);

// 命中特效:一次性事件 → ClientRpc
[ClientRpc]
public void OnHitClientRpc(Vector3 hitPoint) { ... }