- Home /
How can i acess the local Player from Script
I have a Network game and there are a few Scripts who call the Player Script in theier Start() Methods. Looks like this:
void Start () {
FirstPersonController fpc = GameObject.FindGameObjectWithTag("Player").GetComponent<FirstPersonController>();
int i = fpc.GetSecToMax();
}
But in an Network Game there are Multiple Players and i want to know how i can just enter the Local Player (this script work on the Host Player but not on Client Players)
Answer by meat5000 · May 06, 2016 at 12:28 PM
funny you ... if i check if it is the local player WOH CALL this $$anonymous$$ethod aniway i dont know what Player on the server is my local PLayer
Erm, no. Serious me :P
You put this in your code and it will only run on a Client for an object which is its own player. Dont forget that the exact same script will run on all machines and you have to put in these attributes to tell the script what it can and cant run.
A host machine will run both server and client code, treating the client in the same way as remote clients, in essence.
Your server does not have a player, for itself. The client on the server does.
A method which I use, which also utilises the isLocalPlayer attribute is during your Player Setup script, which should run first when a new Player is added to the scene, detect if the player is local or not and then Change the Tag of the player to RemotePlayer if !isLocalPlayer
. The tags of each object do not seem to sync across the network so will happily read differently on each client. This enables you to use
GameObject.FindGameObjectWithTag("Player")
Scripts which use the isLocalPlayer attribute can benefit from labelling the respective functions youve created with the [Client] attribute to make sure the server doesn't attempt to run the code at all. This is necessary for the client on the host machine.
ok that is working perfect, Thanks :) but the scripts are for chaging somethings on a canvas in the sean but the one thing is only shown at the host player and the other thing only at the client ... Is it good to have one Canvas for the HUD in the Game Scean and all player use this Convas ? Or how shult i do that ?