How to get and access script with getComponent

Hi,
I try to access javascript with getComponent(cc.Class).

node
… … …
layer_ui //MainManager.js
… …
layer_popup//PopupManager.js
… …

in MainManager.js
properties: {
… … …
popupLayer: cc.Node,
//END.public
},

… … …
this.popupSrc = this.popupLayergetChildByName( this.popupLayer.name ).getComponent(cc.Class);

In cocos creator, can’t access to other JS in component?

First, forget that getChildByName exists, for your own good. I’m arguing with my coworkers right now about the amount of trouble that it brings…

So, the easiest way to do what you are trying to do is reference the script directly instead of the node. To do so, in the beginning of the file, do a node-like require. You can require just by the file’s name, but insert the path is a good practice for future maintenance.

const PopupManager = require('{PATH_TO_FOLDER}/PopupManager');

So, in properties, you do this:

properties: {
    popupManager: PopupManager
}

and, in your code, you access the instance directly

this.popupManager.doStuff();

Another way to do it is keep the cc.Node type in properties, and access it by getting the component, like you tried to do, it has it’s applications, but for you case, the above would be better

var popupManager = this.popupLayer.getComponent(PopupManager);
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.