Unity-Technologies / com.unity.netcode.gameobjects

Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.
MIT License
2.1k stars 430 forks source link

Bug with IsOwner state, while spawning object in OnNetworkSpawn #2859

Closed WasIOn4ik closed 2 months ago

WasIOn4ik commented 2 months ago

Description: If you spawn a new NetworkBehaviour from another's OnNetworkSpawn, IsOwner property is incorrect

Reproduce Steps: Lightweight example: https://github.com/WasIOn4ik/IsOwnerBug 1) Create new project 2) Create two prefabs 3) Set the first prefab as PlayerObject 4) Spawn the second one in OnNetworkSpawn of first prefab 5) Add debug output in OnNetworkSpawn with check if(IsOwner)

Actual outcome on client: Warning: Trying to spawn NetworkObjectId 4 that already exists!

Expected outcome on client: Info: Object spawned with ownership

Enviroment: OS: Windows 10 Unity version: 2022.13f1 and 2023.2.14f1 Netcode Version: 1.8.1

Additional context OwnerClientID set correctly, but IsOwner is wrong

NoelStephensUnity commented 2 months ago

Hi @WasIOn4ik, Thank you for providing the simplified replication project! (it helps us narrow down the issue faster)

I think the issue you have run into is specific to running as a host. If you want to daisy chain spawning of owned NetworkObjects within a spawned player prefab instance's OnNetworkSpawn method and run in host mode, then I would recommend not using the auto player prefab spawn and handle this in an alternate script. The primary reason is the host will auto-spawn its player prefab while NetworkManager is still spinning up, and it can lead to order of operation issues (like this one).

Attached you will find a slightly modified version of the project you provided with a "PlayerSpawner" script attached to the NetworkManager's GameObject. The NetworkManager was updated so the Player Prefab property is unassigned (i.e. auto-player prefab spawning disabled), and the PlayerSpawner has a PlayerPrefab property that has the FirstObjectPrefab assigned to it.

When you run this you should get no warnings and the second object prefab will be spawned with the appropriate owner (based on your scripts) for both the Host and any clients that connect.

Let me know if this resolves your issue?

IsOwnerSupport.zip

WasIOn4ik commented 2 months ago

Thank you so much for the clear and detailed explanation! Yes, my problem is resolved