Get local player's game object

The new multiplayer API exposes a isLocalPlayer boolean which is useful for checking if the script is being ran on the local player.

Is there anything in the API to get the local player’s game object?

I see PlayerController in the docs which has a reference to the gameobject, but I don’t know how to retrieve this component.

I also see playerControllerId on various components, but no example for retrieving the PlayerController with this.

I know that I can name the local player’s game object and retrieve it using Find or even better tag the local player’s game object and retrieve it using FindGameObjectWithTag.

But is there a better way through the Networking api?

Thanks

1 Like

I like to use the override, OnStartLocalPlayer, which will only be called on NetworkBehaviours on the local player object (and then cache a reference to the gameObject as needed).

1 Like

There is a list of players in the NetworkConnection object - there could be multiple players on a client.

On a client, it is in NetworkManager.client.connection.playerControllers - this is only players on this client. Not all the players in the game.

6 Likes

singleton accessor missing:
NetworkManager.singleton.client.connection.playerControllers[0].gameobject

Did you drag & drop a NetworkManager into your scene ?
Do you use your own NetworkManager and have made your own Awake function ? That kill the singleton too

How can you get all player’s game Object ? Do we have to make our own list ?

From client side, is there a way to access theses player with a synchronized id ? Or do you have to make our own list/id ?

Tanks

I wasn’t talking about an error I received, but about a correction from seanr’s code line, which does not work because it lacks the singleton call.

I’d like to know this, too. Did you figure it out?

Does ClientScene.localPlayers() do what you need?

You can also use the netId propetry of NetworkBehavior and ClientScene.FindLocalObject(NetworkInstanceId netId)

2 Likes

Thanks.
This:

public override void OnStartLocalPlayer()
{
print(“OnStartLocalPlayer”);
GameObject player = ClientScene.FindLocalObject(netId);
print ("player y: " + player.transform.position.y);
}

worked.