- Home /
Piece of code creates unwanted GameObjects in scene
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?
Answer by whydoidoit · Jul 08, 2012 at 07:08 PM
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.
Answer by nventimiglia · Jul 08, 2012 at 07:08 PM
 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);
 }
Answer by Scimitar · Jul 08, 2012 at 10:05 PM
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.
Your answer
 
 
             Follow this Question
Related Questions
gameObject are not referenced 2 Answers
Rotating a Vector3 in Instantiation 1 Answer
How do I make prefab follow a gameobject?(C#) 1 Answer
Distribute terrain in zones 3 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                