Jump to content

How do I get the object by 'key' or 'name'?


San4er
 Share

Recommended Posts

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

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 function

Or:

function createCatProperty() {  this.cat = game.add.image(0, 0, 'cat');}// this.cat is now accessible anywhere in the state

Or 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 image

These 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;});
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...