45 lines
1.5 KiB
Markdown
45 lines
1.5 KiB
Markdown
---
|
||
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 GameObjects(NGO)中的核心类型,用于**持久化复制状态**——当值发生变化时,自动通过网络同步到所有客户端。仅在值真正变化时触发同步(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 实现客户端预测
|