Changing attributes of one script on another script

I’m wondering is there a way to change attributes of one script on another script.
Here are some codes from my script:
In my raycast.js, I have:

var Raycast = pc.createScript('raycast');
Raycast.attributes.add('sphereEntity', {type: 'entity'}); 

And I’m using these lines to change raycast’s attributes in my ui.js but It doesn’t work:

var raycast = this.app.root.findByName('A guy').script.raycast;
var attr = raycast.attributes('HitMaker','entity', null, 
        {
            displayName : 'HitMaker'
        });

The link to my project: https://playcanvas.com/project/534489/overview/my-first-project
The link to my editor: https://playcanvas.com/editor/code/534489?tabs=11477429,11507752,11444736

So you want to add an attribute at runtime?
I never did it but I would try to use the class Raycast instead of its instance, and you should probably call the .add method

1 Like

That’s right.
My intention is to create an UI that when user chooses the entity from UI menu, an entity will be added to raycast.js to perform a ray.
I’m sticking with your way. But I don’t know how to call an variable of ui.js in raycast.js. I’m new to PlayCanvas. Can you show me the way? Thanks a lot.

You don’t need to do what you describe. Let’s look at your attribute declaration code:

Raycast.attributes.add('sphereEntity', {type: 'entity'});

This is how you declare an attribute so that the Editor can expose it in the Inspector panel. This happens when you parse the script in the Editor.

You’re not supposed to create attributes like this at runtime! For a runtime created attribute, you simply need to do:

var HitMaker = pc.createScript('hitMaker');

HitMaker.prototype.initialize = function () {
    this.myNumber = 0;
    this.myEntity = new pc.Entity();
};

Or if you want to access those properties from another script, you simply do:

var AnotherScript = pc.createScript('anotherScript');

AnotherScript.prototype.initialize = function () {};

AnotherScript.prototype.initialize = function () {
    var hitMakerEntity = this.app.root.findByName('Hit Maker');
    console.log(hitMakerEntity.script.hitMaker.myNumber);
    console.log(hitMakerEntity.script.hitMaker.myEntity);
};
2 Likes