Novice Flashpunk user / Problem with world.getInstance()


(Wellarrived) #1

Hi everyone,

While it seems that i could correctly use an instance of my Player in another class to access his properties, i’m now facing a problem when using world.getInstance() in another Class.

private function join_world_tab() : void
	{
		if (_player_instance == null)
			_player_instance = world.getInstance("player") as Player;
		else
			_player_instance.add_new_world_entity(this);
	}

_player instance is declared like this, in a Class called Content :

private var _player_instance : Player;

I got an error message saying that i can’t acess a null property, the problem is that a similar portion of code works properly elsewhere, like this :

if (collide("player", x, y))
		{
			if (_player_instance == null)
			{
				_player_instance = world.getInstance("player") as Player;
			}
			
			else
			{
				this._player_instance.setOnFloor(true);
			}			

Anybody knows what is going on ? I’m kinda lost here. Thanks !


(JP Mortiboys) #2

To use getInstance you have to set the name property of the entity - a simple this.name = "player" inside the Player constructor would do the trick.

Alternatively, instead of using getInstance you could use world.classFirst(Player), or world.typeFirst("player") - the former references by class, the latter by collision type (which I can see you’re using).


(Wellarrived) #3

I did that, and it works for one case, but not for the other : /


(JP Mortiboys) #4

Is this Content class a subclass of Entity, and is it added to the same world?


(Zachary Lewis) #5

While that will work, I think there might be a bigger issue with @Kark123’s system design.

@Kark123, you’ve a class Player and a reference to a Player that is added to a World in Content, right? This seems overly complex to me. What is your reasoning for not maintaining a reference to a Player in a World?

For your second case, you can save a reference to the collided Player instead of trying to get a reference.

// Entity.collide will return the first entity collided with,
// or null if no collision occurred.
var collidedPlayer:Player = Player(collide("player", x, y));

// If collidedPlayer does exist, there was a collision.
if (collidedPlayer != null)
{
  // We already have a reference to the collidedPlayer, so use it!
  collidedPlayer.setOnFloor(true);
}

(Wellarrived) #6

Thanks for the tips guys, i also think that conserving a Player instance in my World class is much more useful and easy to implement. So i proceed to maintain a private reference in my World class, with a public getter. I get the same exception when i try to use it.


(Jacob Albano) #7

Are you sure you’re initializing the instance?