[SOLVED] Can You Set An Editor Attribute In Script?

I’m writing some code that checks to see if an attribute on an entity is null, and if it is, set it to the correct element.

This is used in case a developer forgets to set the target for an entity variable in the editor’s hierarchy.

I’ve noticed in my testing that the attribute will continue to be null after setting it to the element, is there a way to achieve this? I assume there’s a simple flaw in my logic below…

//Variable exposed in editor at the top of the script
ExampleScript.attributes.add('notSetInEditor', { type: 'entity' });

//On initialize, find the Text element attached to this entity and set it to the attribute since it wasn't set up in editor

ExampleScript.prototype.initialize = function() {
    
    if( !this.notSetInEditor && this.entity.element.text )
    {
        this.notSetInEditor = this.entity.element.text;
        console.log( "this.notSetInEditor = " + this.notSetInEditor );
    }
    
};

You can just set the value to the attribute. It wont update the editor view, but if you can fallback to a default value it will atleast work in playmode. Although I can imagine, thats on the todo list for the editor extensions.

What I usually do is check for all my required input values in the initilize, or a dedicated variable setup function and make a console warning, if something is missing. Or return with an error message, if its required.

To set an entity to your variable you would need to look up the actual entity in the scene by its name. Like so:

this.notSetInEditor = this.app.root.findByName( this.entity.element.text );

and maybe add some helpful console warning like so

console.warn( "No whatEver entity was defined in the editor, falling back to the default entity: " + this.defaultEntity );

Hope that helps.

Greetings,

Martin

Testing out setting the variable seems to provide the same null result when I check it in the debug play mode on the browser console.

I’ve made a test to show this use case, if anyone can figure it out, let me know.

https://playcanvas.com/project/509667

You dont have an entity in your scene with the name you are looking for.

this.app.root.findByName

Is looking for an entity with the name you supply within the brackets. In your case this would need to be “Text” but you look for an entity with the name “FPS:”. As this does not exist in your scene, the script returns null :wink:

Thanks swatty, I fixed the entity search, and the script now works.

No problem, glad I could help :+1: