- Home /
What is the best way for scripts to find the player C#
Hello all, i'm currently in the process of adding multiplayer into my game and have found an issue where many of my scripts reference scripts attached to the player which is declared in the void Start. if the player is not in the scene when the scripts use void Start then the player is never found so none of my scripts work.
so long story shortish how can i make my scripts say "when the player has spawned
GameObject Player = GameObject.Find("Player");
CharacterControler characterControler = Player.GetComponent<CharacterControler>();
then continue with script". the only idea i had was making it check in the update and using something like "if player != null" but i imagine that would be very wasteful.
thanks for any help.
ps. im using Photon Networking if that makes any difference.
Answer by etaxi341 · Jul 24, 2014 at 04:40 PM
You could use it in the Fixed Update so it wouldnt waste that much power. Or you could have one script that sets the player for all scripts and after thats done it deletes itself. So it only gets run if the player hasnt been found
thanks for the reply, is there any way to change variables in all scripts in the scene or at the very least all scripts with a certain name?
I am sorry but I dont think so. You would have to "link" this Scripts to this main script. So you would do
public Script1 script1;
public Script2 script2;
and then you can add this scripts from the gameobjects in the inspector.
But thats such a big expense. So i would just use the thing @robertbu said and put it in FixedUpdate. So it will only run 30times a second
I disagree that 'FixedUpdate()' is the right solution. Only put it in FixedUpdate() if your references to the player is in FixedUpdate(). FixedUpdate() can run faster or slower than Update(), so if you put it in FixedUpdate() you could end an error when you attempt to access the game object.
well i changed everything up so it worked the way robertbu suggested and it took some tweaking but it works now :) thanks a ton for all the help (also i dont know how i can change his comment to an answer sorry)
Answer by robertbu · Jul 24, 2014 at 05:07 PM
Note that GameObject.FindWithTag() is far more efficient than GameObject.Find(). So in Update() you should be able to:
if (player == null) {
player = GameObject.FindWithTag("Player");
}
thanks so much for this, took a bit to get it done but it worked great
Your answer
Follow this Question
Related Questions
GameObject.Find, When it is Called? 1 Answer
Multiplayer cant see host player C# 0 Answers
Multiplayer: client cant see host C# 0 Answers
A node in a childnode? 1 Answer
RPC called by OnPhotonPlayerConnected doesn't work 2 Answers