Trouble with passing values to the instance in world.create()


(Jacob) #1

I have an Array that stores instances of a class called Block. The array is populated using myArray.push(world.create(Block));. Block contains a function: public function setup(_type:String, _color:uint):void. I want to pass values to the Block instance in the myArray.push(world.create(Block)); line of code.

I’ve tried:

var subType:String = "blueBlock";

var otherColor:uint = 0x1A1A1A;

myArray.push(Block(world.create(Block)).setup(subType, otherColor));

But when I go to access properties of the instance in that array index, I get an error on that line:

myArray[myArray.length - 1].x = x;
[Fault] exception, information=TypeError: Error #1010: A term is undefined and has no properties.

However, this works fine:

myArray.push(world.create(Block));

myArray[myArray.length - 1].type = subType;

myArray[myArray.length - 1].img.color = otherColor;

myArray[myArray.length - 1].x = x;

Can someone please help?


(Jean) #2

I believe it’s because push returns an Object instance and not a Block instance.


(Justin Wolf) #3

world.create() will always return the Entity that was created, whereas Block(world.create(Block)).setup() likely has no return (void), so you’re pushing nothing into your array, thus resulting in the errors.

Head to your setup() function on your Block class and change the :void to :Block and then at the bottom of the function throw in a return this and see if that solves your issue.

public function setup(yourParameters:*):Block
{
      // do your setup stuff

      // return this instance of Block
      return this;
}

(Jacob) #4

justinwolf, that works! Thank you very much. And I mostly understand what’s happening there.