Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved DontDestroyWithOwner and IsLocalPlayer on hosts

Discussion in 'Multiplayer' started by jackward84, Jul 16, 2023.

  1. jackward84

    jackward84

    Joined:
    Jan 26, 2017
    Posts:
    87
    I am trying to leave the player network objects in scene when they disconnect, and if they reconnect give the player object back to them. Despawning the object and respawning on reconnection isn't what I want because it essentially would let players alt f4 if they are in any kind of danger - I want the object to remain in the world and be interacted with normally by everyone else as if nothing happened.

    So first step, as per docs, is set the player object to DontDestroyWithOwner = true. This works fine, the object isn't destroyed when the client disconnects and the object can still be interacted with by other players/enemies.

    However the problem I noticed with this, is now IsLocalPlayer returns true for this object on the host. I'm not sure what to do with this, since I have IsLocalPlayer checks all over my codebase for this object type, which would lead to weird behaviour for hosts. I do have a static reference to who the local player is, which I can add to IsLocalPlayer checks, but this isn't very elegant since I would basically need to reference the root player object/script in every network component to check that IsLocalPlayer is actually the spawned local player and not just an object that the host currently has ownership of. I am wondering if there is a simpler/built-in way that I haven't thought of.
     
  2. NoelStephens_Unity

    NoelStephens_Unity

    Unity Technologies

    Joined:
    Feb 12, 2022
    Posts:
    48
    @jackward84
    The best way to determine if a NetworkObject with NetworkObject.IsPlayerObject set is to check that NetworkObjet against the NetworkManager.LocalClient.PlayerObject on the host side. The NetworkManager.LocalClient.PlayerObject is always the player object assigned to the local client.
     
    jackward84 likes this.