How can i create a serializable custom enum?

Hi, I have this error “Argument of type ‘typeof SectionLevel’ is not assignable to parameter of type ‘Constructor | TypeResolver | (Constructor | TypeResolver) | null | undefined’.” in this script

export class UISections extends Behaviour {
    

    @serializable(SectionLevel)
    sectionLevel!: SectionLevel;
}

enum SectionLevel {
    MainSection,
    Section,
    ObjectSection
}

Original Post on Discord

by user 690302479664939071

Hello there – we have an experimental AI bot :robot: that might be able to help you with your question. Would you like to try this out?

How it works:
Reply to the messages of the bot that end with a thread_id to interact with it and ask follow-up questions. You can also mention the bot directly in this channel to get help.

Help requested: please wait a moment


Here is what I found for you :brain: Discord

Hello Maxi Brunetti, it appears you have encountered a TypeScript error related to the use of decorators with enum types in your UISections class. Enums are a special case when it comes to serialization in TypeScript.

As per the Needle Engine documentation, the @serializable() decorator is used to deserialize components when loading a scene from a glTF, and it takes optionally the type which should be deserialized. However, in the case of enums, it’s not straightforward to use them with decorators as they do not result in a type that can be instantiated like a class.

To resolve this, you don’t need to pass the enum type to the @serializable() decorator. Instead, use it without any arguments for primitive values like enums. Enums are serialized as their numeric values by default in TypeScript.

Here’s the corrected code:

export class UISections extends Behaviour {
    @serializable()
    sectionLevel!: SectionLevel;
}

enum SectionLevel {
    MainSection,
    Section,
    ObjectSection
}

Make sure the enum is declared before it’s used in the class to avoid any reference errors, and apply the @serializable() decorator without passing the enum type as a parameter. If you require a different serialization method for the enum, you might need to implement custom serialization logic.

1 messages left GPT 4
thread_OJWbfsVZOVvC8WZ6oZXASlv1

Hi, you need to declare the enum manually on your C# somewhere if it doesn’t exist in unity.

Since we only automatically generate component types for unity and not any other types

by user 690302479664939071