So there are some ways to āReferenceā Entities.
Suppose I want to click a button and then make a menu appear, like a settings menu.
There are some ways to accomplish that.
By Name
You could have a button script that when itās clicked, you could call:
this.app.root.findByName('Menu');
This would look for an Entity in the Scene Tree named Exactly Menu, and then access the script from there and make it appear. The problem with this approach is that the Name of the Object has to match otherwise it wonāt work, in a big project it may become very confusing knowing what needs to be named what without looking at the code.
By Reference
This one I just tried, on the button script you could add a Attribute like this:
ButtonScript.attributes.add('menu', {type: 'entity'});
then you could access the menu script from there, something like this:
this.menu.script.menuScript.method()
Then on the Editor you just drag n drop the menu entity on the Property that would appear on the Script object on the Button Entity.
In this way you wonāt have any naming problems as you would with the previous solution but this makes the relationships specific, and you have to manually bind them in the editor, and if you forget to do this, things will also not work.
The Broadcast way
The final way is using events that you may fire from some scripts while other scripts are listening to them.
On the button and menu example, the button would have something like this:
this.app.fire('menu:open');
and on the Menu script you could have something like this:
var onOpenMenu = function() {
// Open the Menu
};
// listen for the player:move event
this.app.on('menu:open', onOpenMenu);
// remove player:move event listeners when script destroyed
this.on('destroy', function() {
this.app.off('menu:open', onOpenMenu);
});
On this approach you donāt need any explicit reference to anything, it becomes way more easy and flexible, but must be used cautiously because on a larger projects, the number of events being fired may make debugging the game difficult.
This seems to be the preferred way on the PlayCanvas ecosystem, you can read more about it here:
https://developer.playcanvas.com/en/user-manual/scripting/communication/
Sorry I donāt know if itās clear enough, and @yaustar may correct me if I said anything wrong.
Thanks!