Feature Request: Add `getObjectById()` method
jcollard opened this issue · comments
Currently, there doesn't seem to be a way for object to easily talk to each other.
For example, I'm trying to make a snake game and I cannot have my "player" check if it is colliding with a "food" because it cannot reference the food object.
Hack:
To get around this, I add this cod to the start
method of each of my objects:
if (!window.myObjects) {
window.myObjects = {};
}
This gives me a way to access object. Then, I can capture the scope using anonymous functions:
head.getPosition = () => getTilePos();
head.levelUp = () => levelUp();
window.myObjects.head = head;
Then in my food object, I can reference my head (player) object like this:
let headPos = window.myObjects.head.getPosition();
let pos = getTilePos();
if (pos.x === headPos.x && pos.y === headPos.y) {
respawn();
window.myObjects.head.levelUp();
}
It's a little convoluted. And has a major downside that I cannot really have two "head" objects. To do this, I would need to write a hack to check which one is instantiated first.
Proposal:
- Add an
id
field to each instance of a GameObject. Theid
must be unique and can be set manually in the editor when the instance is selected:
By default, the id
could be a generated UUID. You would need to have error handling to ensure that two objects don't have the same name / auto rename with -2 or -3 if they do.
- Add a global
Scene
object that has agetObjectById()
method. For example:
CodeTrain.Scene.getObjectById("SomeIdHere");
I'd love your thoughts!
Thanks for the request, this looks like a great addition! I'll get to work on it.