Common Pitfalls
Common Pitfalls
1. Modules Must Be Fields or Properties
Network modules must be declared as a field or property on a NetworkIdentity.
Do not create them dynamically or store them in collections.
public class MyNetworkObject : NetworkIdentity
{
public SyncVar<int> health; // โ
Correct
private SyncList<string> names; // โ
Correct
// โ Incorrect: Do not use lists of modules
public List<SyncVar<int>> invalidList;
}
2. Editor Serialization
Modules can be serialized and shown in the Unity Editor.
Just mark them with [SerializeField] or make them public.
[SerializeField]
private SyncVar<int> health; // Will show up in the Inspector
public SyncList<string> names; // Also visible if public
3. Initialization: Use OnInitializeModules()
You can create, override, or initialize modules in theprotected virtual void OnInitializeModules() callback.
This runs before networking sends data or assigns IDs.
protected override void OnInitializeModules()
{
health = new SyncVar<int>(100);
// Custom initialization here
}
4. Do Not Replace Modules After Spawn
Once spawned, never assign a new module instance to a field/property.
Doing so will break networking or cause undefined behavior.
Modules are meant to be constant after spawn.
// โ Don't do this after spawn:
health = new SyncVar<int>(200); // Will break networking!
5. Nesting Modules
You can nest modulesโmeaning a network module can use other modules like SyncVar as fields or properties.
public class MyModule : NetworkModule
{
public SyncVar<int> score; // โ
Allowed
}
Do not create circular dependencies.
If Module A uses Module B, and Module B uses Module A, it will break.
Nesting must form a tree, not a loop.
// โ Not allowed: Circular reference
public class ModuleA : NetworkModule
{
public ModuleB b;
}
public class ModuleB : NetworkModule
{
public ModuleA a; // This creates a cycle and will cause compiler error
}
6. No Lists of Modules
You cannot create a list or array of modules.
Modules must be declared as fields or properties at compile time.
// โ Not allowed:
public List<SyncVar<int>> moduleList;
// โ
Allowed:
public SyncVar<int> health;
public SyncVar<int> mana;
7. Module Events
Modules have similar events to NetworkIdentity, such as:
OnSpawnedOnOwnerChangedOnDespawned
You can use these for custom logic inside your modules.
public class MyModule : NetworkModule
{
protected override void OnSpawned() { /* ... */ }
protected override void OnOwnerChanged(..) { /* ... */ }
protected override void OnDespawned() { /* ... */ }
}