Accessing Entity!?


(Ethan Smythe) #1

Hey guys i would like to access my player variable named “_player” (not the class the entity) in my GameWorld class! whats the easiest way to achieve this?


(David Williams) #2

How is it currently being added to the world?


(Ethan Smythe) #3

in the GameWorld class i am adding my player class to it “add(new Player);”


(rostok) #4

I add static variable to classes that should be visible from global scope.

	public class Player extends Entity
	{
		public static var instance:Player = null;
		
		public function Player()
		{
			super();
			instance = this;
		}
	}

You can also detect in constructor if instance is not null to avoid another player creation - then this would match a Singleton pattern. Other way is to give a player a name and access it by FP.world.getInstance(). If you will use FP.world.getType() you will get results in bulk. Note that getInstance() uses Dictionary that implements hashmap so results are given really fast.

Finally you can assign it in GameWorld (declare _player in a class)

_player = add(new Player);

(Ethan Smythe) #5

yeah i understand but even if my variable is static it still wont show in my game world class :frowning:


(Sharp) #6

If i recall well, entities can be assigned by id. So just assign an id with entity.name and recover the entity in the world with world.getInstance(“name”)


(Jacob Albano) #7

getInstance() is the best approach, in my opinion. Using static variables is a good way to get yourself in trouble because you can change them from anywhere, so it’s hard to track down errors related to setting them at the wrong time.

var player:Player = new Player();
player.name = "player";

add(player);

and later…

var player:Player = world.getInstance("player") as Player;
if (player)
{
    //  the player exists in the world, now do something with it
}

This is all covered in the tutorial Accessing Entities.


(Alex Larioza) #8

I usually just give my world class a private member variable with a public getter (and no setter):

// game world class
private var _player:Player
public function get player():Player { return this._player; }
...
// some other entity
GameWorld(world).player