x


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?

more ▼

asked Jul 08 '12 at 07:02 PM

Scimitar gravatar image

Scimitar
3 2

(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first

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.

more ▼

answered Jul 08 '12 at 07:08 PM

whydoidoit gravatar image

whydoidoit
33k 11 23 100

(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Jul 08 '12 at 10:05 PM

Scimitar gravatar image

Scimitar
3 2

(comments are locked)
10|3000 characters needed characters left
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);
}
more ▼

answered Jul 08 '12 at 07:08 PM

nventimiglia gravatar image

nventimiglia
277 7 13 17

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4151
x2084
x1672
x120

asked: Jul 08 '12 at 07:02 PM

Seen: 297 times

Last Updated: Jul 08 '12 at 10:05 PM