San4er Posted June 29, 2014 Share Posted June 29, 2014 Hello, I've just started using Phaser How do I get my object by it's "key" or "name" or "id"?For example:function createCat(name){ var img=game.add.image(0,0,'cat'); img.name=name;}createCat('Lawnmover');createCat('Strawberry')//now how can I use it outside of that function? Is there something like this?var myCat=game.getObjectsByName('Lawnmover'); Link to comment Share on other sites More sharing options...
lewster32 Posted June 30, 2014 Share Posted June 30, 2014 Just use normal JavaScript vars or properties - there's no unique index to get an object added to the scene, as the renderer uses a hierarchical tree of nested objects called a 'scene graph'. Depending on how you're writing your code, either declare the var outside of the function, or make it a property of 'this' which will usually be your state:var myCat;function createCat() { myCat = game.add.image(0, 0, 'cat');}// myCat is now accessible outside of the createCat functionOr:function createCatProperty() { this.cat = game.add.image(0, 0, 'cat');}// this.cat is now accessible anywhere in the stateOr finally using the function to return what it creates:function createCat() { return game.add.image(0, 0, 'cat');}var myCat = createCat();// myCat now contains the imageThese methods can be inflexible however as they mean you have to manage every instance separately, so a usually better way is to use groups:var catGroup = game.add.group();function createCat() { var cat = game.add.image(0, 0, 'cat'); catGroup.add(cat);}// create 3 catscreateCat();createCat();createCat();// loop through the catGroup and do something with each cat in itcatGroup.forEach(function(cat) { cat.x = game.world.randomX; cat.y = game.world.randomY;}); clark 1 Link to comment Share on other sites More sharing options...
San4er Posted July 3, 2014 Author Share Posted July 3, 2014 Thanx Link to comment Share on other sites More sharing options...
Recommended Posts