Is it possible to use a dynamic enum defined in a json asset for an attribute

Hi all,

I have an enumeration that depends on a json asset inside the project and I would like to be able to define the enum of an attribute inside the editor based on the content of that json file. So basically if I add new items inside the file the enum should update on the script in the editor after a re-parse.

const bodyColorIds = [] as Record<string, unknown>[];
const assets = pc.Application.getApplication().assets;
const patternColorMapping = assets.find("BodyPatternsColorMapping.json").resource as Record<string, RgbColor[]>;
Object.keys(patternColorMapping).forEach((key) => {
  bodyColorIds.push({ key: key });
});

@createScript("MonsterPreviewTools")
export class MonsterPreviewTools extends ScriptTypeBase {

  @attrib({
    title: "Body Color Id",
    type: "string",
    default: "Color_5001",
    enum: bodyColorIds,
  })
  bodyColorId: string;

  ......
}

I’m getting an undefined object when re-parsing the script, on the second line, which I assume is because when the module is loaded the code above the class definition is ran once but there is no instance of the pc.Application yet. I tried retrieving the editor instance as well with something like this window.editor but with no success either.
Is it possible to get the assets from the Editor somehow and load the json file to parse?
So in the end what I’d like to have is possibility of dynamically creating attributes based on assets I have. Is there a way to achieve that?

Thanks!

Hi @heretique,

I think that’s not possible, the JS parser will only scan the code and not actually execute it (load and access the asset).

@yaustar may be able to confirm this.

Afraid it’s not possible as it takes whatever values is in the array when parsing

1 Like

If I’m not mistaken the code above/outside the class definition will be ran when the module is loaded first time probably this happens when we re-parse but I’m note sure how could I get access to the assets at that point.

I was wondering if it is possible to update the attributes in the scripts’s initialize method as an alternative?

No, as initialize is not called when the script is parsed.

The only way I can think of doing this is if the JSON is defined as a JSON object in the same script file and that is used to construct the enum attributes