com.unity.netcode.gameobjects
com.unity.netcode.gameobjects copied to clipboard
NetworkObject parent not replicated if Instantiated with parent
Description
Instantiating a NetworkObject prefab and passing in a NetworkObject parent causes the client to error with NotServerException.
Reproduce Steps
- Start server
- Connect with client
- Instantiate a NetworkObject prefab on server. Store as
someOtherNetworkObject. (This also works with an in-scene NetworkObject). - Instantiate a NetworkObject prefab on server with
Instantiate(prefab, Vector3.zero, Quaternion.identity, someOtherNetworkObject).
Actual Outcome
Client produces error of NotServerException: Only the server can reparent NetworkObjects and NetworkObject is not reparented.
Expected Outcome
Object is reparented on client with no error.
Environment
- OS: Windows
- Unity Version: 2021.3.2f1
- Netcode Version: 1.0.0-pre.9
Additional Context
As a workaround, instantiating the GameObject, spawning, then reparenting works. Ideally though this would work automatically, or at least give a message that spawned NetworkObjects should have a null parent.
Backlog MTT-4082
@andriyDev
Unfortunately, we currently do not support parenting directly when instantiating due to several reasons.
The current recommended solution is to use NetworkObject.TrySetParent to avoid this issue.
There are some updates to parenting that should be in the next update that resolve several parenting related issues, but it still requires you to use NetworkObject.TrySetParent when parenting.
It's quite the annoyance that spawning with parent isn't possible... the network message to spawn should include the parent so that's an atomic operation.
There's a toooon of other code that must suddenly wait to run because nothing can be spawned with its parent already set.
@zachstronaut That area is something I plan on revisiting soon, but we have two releases (the experimental NGO v2.0.0) and the up-coming v1.9.0 that have taken a large chunk of my time.
I need to still revisit the initial reasoning behind this, but off of the top of my head there was the concern of complex nested NetworkObjects where the 1st or 2nd (+) generation GameObjects didn't necessarily contain a NetworkObject component... which under that scenario would either become a hard requirement (i.e. directly parented under) or we would need to come up with a way to uniquely identify each child generation (especially if it is a pre-parented dynamically spawned set of NetworkObjects) to associate serialized data with a specific child nested (n) generations deep.
But I do promise to look through that area in the near future as it is a pain point in development and does deserve some reconsideration on how it could be better organized (but also consider that if the fix for this ends up in a breaking change relative to 1.x.x versions it might need to be a v2.x.x only thing).