我目前遇到以下问题。 我正在尝试访问场景中的图层,从而访问我在该图层中设置的元素。在这种情况下,我想访问Layer中的conv_label来设置文本。
我是通过扩展cc.Class的ConversationClass来做到这一点的。 当我尝试通过变量访问该层时它不起作用或使用getChildByName或Tag它不起作用(值始终为null)。
这是ConversationClass中的一个方法,我可以控制台记录的流量没有任何问题,但我设置的任何变量都没有出现在当前场景中。在这种情况下,名称是“conv_layer”,我可以通过使用数组调用来访问子节点,但这看起来并不是一个好方法,而且非常令人困惑。
我试过了:
currentscene.children[0].children[3] will give me the right element.
currentscene.conv_layer.getChildByName("text") says conv_layer does not exist
currentscene.children[0].getChildByName("text") returns null
有谁知道如何解决这个问题,或者可以告诉我我的想法出了什么问题?
不确定是否重要,但我以下列方式调用场景(现在)。
cc.LoaderScene.preload(conversation_load, function() {
cc.director.runScene(new ConversationScene());
this.startGame();
}, this);
这是我想要访问的地方
startConversation: function(conversation) {
this._conversationObject = conversation;
this._currentScene = cc.director.getRunningScene();
console.log(this._currentScene); // Shows current scene object (doesn't have conv_layer property)
if(scene !== null)
this._currentConversationLayer = scene.conv_layer; // Returns null
},
这是我的场景:
var ConversationScene = cc.Scene.extend({
conv_layer: null,
onEnter: function() {
this._super();
this.conv_layer = new ConversationLayer();
this.conv_layer.setName('conversation');
this.conv_layer.setTag(1);
this.addChild(this.conv_layer);
}
});
这是我的图层:
var ConversationLayer = cc.Layer.extend({
ctor: function() {
this._super();
this.init();
},
init: function() {
this._super();
var winSize = cc.director.getWinSize();
GD.current_conversation = conversation1;
this.background = new cc.Sprite();
this.background.anchorX = 0.5;
this.background.anchorY = 0.5;
this.background.setPositionX(winSize.width / 2);
this.background.setPositionY(winSize.height / 2);
this.addChild(this.background);
this.girl = new cc.Sprite();
this.girl.anchorX = 0;
this.girl.anchorY = 0;
this.addChild(this.girl);
this.text_background = new cc.Sprite(resources.conversation_interactive_assets, cc.rect(0,0,1920/GD.options.scale,320/GD.options.scale));
this.text_background.anchorX = 0.5;
this.text_background.anchorY = 0;
this.text_background.setPositionX(winSize.width / 2);
this.text_background.setPositionY(0);
this.addChild(this.text_background);
// Left
this.conv_label = new cc.LabelBMFont("", resources.font);
this.conv_label.anchorX = 0;
this.conv_label.anchorY = 0;
this.conv_label.setPositionX((winSize.width - this.text_background.width) / 2 + 20);
this.conv_label.setPositionY(this.text_background.height - 30);
this.conv_label.color = cc.color.BLACK;
this.conv_label.setName('text');
this.addChild(this.conv_label);
}
});
答案 0 :(得分:0)
问题是所有事情的加载顺序。
似乎场景是以异步方式加载的,因此将调用下一个函数,但此时不存在任何层。
通过在类本身内创建并调用onSceneEnter来解决它。