Trying to use a global array in an attribute

When I work in Unity I’m a big fan of creating global Enums for everything (buttons, scenes, states…), and then use those Enums in public variables. So I can just select a button-id from a drop-down and avoid typing in names in strings etc.

Trying to replicate this in PlayCanvas I’ve declared a global array in one script like so:
var buttonIDs = [{Enter : “Enter”}, {Exit : “Exit”}]; // a ton of buttons

And then in another script I’m trying to use the above array in an attribute:

ButtonBaseClass.attributes.add(‘buttonID’, {
type: ‘string’,
enum: buttonIDs

…but no luck. When parsing the script in PC I get an error saying that buttonIDs is not defined. But I can obviously use the array in other parts of the same script.
Does anyone know how to get around this? It would be a massive timesaver if this could work.

@MrOliv it has to be buttonIDs = [{Enter : “Enter”}, {Exit : “Exit”}]; which makes the variable global.

Thanks @Fus_ion but it doesn’t seem to help unfortunately

I think what’s happening here is that the JavaScript editor finds everything ok (which it is), but when the script is attached to an Entity and PlayCanvas parses the code to create the attribute, it just looks at what’s in that script and doesn’t realize that the array is defined elsewhere.

Unfortunately the parsing only works on a per physical script file level. The only way I can see around this is to put multiple script types in the same file or at the least put all the ‘createScript’ and attributes in the same file that require access to the global variable. The latter would also mean that script loading order is important so that functions are defined after the createScript calls.

1 Like