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

45 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "NetworkVariable"
type: concept
tags: [networking, unity, ngo]
sources: [unity-multiplayer-engineer]
last_updated: 2026-04-26
---
## Aliases
- NetworkVariable<T>
- NV (abbreviation)
## Definition
`NetworkVariable<T>` 是 Unity Netcode for GameObjectsNGO中的核心类型用于**持久化复制状态**——当值发生变化时自动通过网络同步到所有客户端。仅在值真正变化时触发同步dirty check
## Usage Rules
| 场景 | 应使用 |
|------|--------|
| 持久化、需要同步的状态 | `NetworkVariable` |
| 一次性事件、触发通知 | `ClientRpc` / `ServerRpc` |
**核心原则:持久化用 NetworkVariable一次性事件用 RPC不可混用。**
## Bandwidth Considerations
- **避免在 Update() 中重复设置相同值**——触发无意义的网络同步
- 对高频数值使用差分压缩(`INetworkSerializable`
- 非关键状态(血条、分数)限流至最高 10Hz
## Example
```csharp
// 健康值:持久化 → NetworkVariable
public NetworkVariable<int> PlayerHealth = new(100,
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Server);
// 命中特效:一次性事件 → ClientRpc
[ClientRpc]
public void OnHitClientRpc(Vector3 hitPoint) { ... }
```
## Related Concepts
- [[ServerAuthority]]: NetworkVariable 体现服务器权威
- [[BandwidthManagement]]: 优化 NetworkVariable 使用
- [[ClientPrediction]]: 结合 NetworkVariable 实现客户端预测