无法获得节点的property

官方的摘星星游戏实例,在Game.js里写

spawnNewStar: function() {
    newStar.getComponent('Star').game = this;
},

然后在Star.js里写

 getDistance :function()
{
    var playerPos = this.game.player.getPosition();
},

为什么游戏无法运行并报错
Star.js:13Uncaught TypeError: Cannot read property ‘player’ of undefined
我已经把Game.js里所有的组件都已经挂到Canvas上了。
Star.js也挂到star的prefab上了,还是找不到错误出在哪

Game.js里

properties:{
     player:
    {
        default:null,
        type:cc.Node,
    },

把项目打包发上来看看吧,这样描述看不出问题

StarProject.zip (2.9 MB)

在Star.js里使用alert(this.game);得到的结果是undefined
是说明生成的newStar实例里没有game这个属性吗?
但是在Game.js里alert(newStar.getComponent(‘Star’).game)的返回结果是Object
难道Game.js里newStar.getComponent(‘Star’).game 不等于Star.js 里的 this.game ???
中间出了什么问题吗

找到问题了,你的Star.js的onLoad里调用了this.getDistance(),而this.getDistance里又使用了this.game。但是这些都是在Game.js里this.node.addChild(newStar);的时候执行的,此时还没有执行过newStar.getComponent(‘Star’).game=this;因此出错。你要避免在Star.js的onLoad执行过程中访问this.game,或者把newStar.getComponent(‘Star’).game=this;移到this.node.addChild(newStar);前面。

另外,通过alert()看返回结果不太方便,用cc.log(newStar.getComponent(‘Star’).game),可以在浏览器控制台(按F12呼出)内看到这个对象的详细信息。包括你这个错误的堆栈信息也可以在浏览器控制台看到。

onLoad 适合查找 Hierarchy,给关联变量赋值。
start 适合访问关联变量。
这样能避免出现脚本执行顺序不对的错误。

果然是脚本执行顺序不对,非常感谢您的解答!!