Hi, I’m using the following code to get a reference to the local player character (as opposed to remote players):
public static GameObject FindLocalPlayer() {
GameObject localPlayer = new GameObject();
GameObject[] Players = GameObject.FindGameObjectsWithTag("Player");
foreach(GameObject Player in Players) {
if(Player.networkView.isMine) {
localPlayer = Player;
}
}
if(localPlayer) {
return localPlayer;
}
else {
return null;
}
}
For some reason, however, this code instantiates an empty GameObject in the scene every time it is called. I can only assume it is the line
GameObject localPlayer = new GameObject();
but I don’t understand how this Instantiates a GameObject called “new Game Object” at (0,0,0) in the actual scene. This doesn’t usually happen when I’m declaring a GameObject variable, so what am I doing wrong here?
public static GameObject FindLocalPlayer() {
GameObject localPlayer;
GameObject Players = GameObject.FindGameObjectsWithTag(“Player”);
foreach(GameObject Player in Players) {
if(Player.networkView.isMine) {
localPlayer = Player;
}
}
if(localPlayer) {
return localPlayer;
} else {
return null;
}
}
Or perhaps using System.Linq;
public static GameObject FindLocalPlayer() {
var Players = GameObject.FindGameObjectsWithTag("Player");
return Players.SingleOrDefault(o=> o.networkView.isMine);
}
You aren’t declaring a variable with that line you are creating a game object and assigning it to a variable. It appears this code is looking for a player game object that is local and creating one if there isn’t one.
Well I solved it by changing:
GameObject localPlayer = new GameObject();
to:
GameObject localPlayer = null;
Thanks for the help, both of you. I didn’t realize new GameObject() would actually place an empty GameObject in the scene.