最近剛剛開始學習cocos creator。按照教程寫了一個flappy bird的腳本。在實作管道預制體的時候遇到了一個問題。我在管道腳本里寫的init()方法無法正常運行,在Chrome下運行時顯示Uncaught TypeError: Cannot read property 'init' of null
以下是生成管道預制體的方法,程式在第二句報錯了,求大神解答

spawnPipes:function()
{
//生成上管道實體
var pipeUp = cc.instantiate(this.pipePrefabs[0]);
//定義為上端型別
pipeUp.getComponent('Pipe').init(0);
//獲取管道高度
var pipeHeight = pipeUp.getComponent('cc.Sprite').spriteFrame.getRect().height;
//設定上端管道的橫向起始位置
pipeUp.x = this.size.width/2 + this.pipeMaxOffsetX;
//設定上端管道的縱向起始位置
pipeUp.y = Math.floor(Math.random()*this.pipeMaxOffsetY)+pipeHeight/2;
//生成下管道實體(以下同理)
var pipeDown = cc.instantiate(this.pipePrefabs[1]);
pipeDown.getComponent('Pipe').init(1);
pipeDown.x = this.size.width/2 + this.pipeMaxOffsetX;
var pipeGap = Math.floor(math.random()*(this.pipeMaxGap-this.pipeMinGap))+this.pipeMinGap;
this.pipesNode.addChild(pipeUp);
this.pipesNode.addChild(pipeDown);
this.pipes.push(pipeUp);
this.pipes.push(pipeDown);
},
uj5u.com熱心網友回復:
很明顯的問題,pipeUp.getComponent('Pipe')得到的東西是一個null。那就很明顯了,你確認是否可以通過"Pipe"這個key來拿到你需要拿的東西,我猜你并沒有對你的那些控制元件設定名字
uj5u.com熱心網友回復:
你自己加斷點看看啊,或者 console.log 看看你pipeUp.getComponent('Pipe') 是否獲取成功了,如果沒成功,再看看你的creator是不是弄錯了uj5u.com熱心網友回復:
難道不是應該 新創建預制物件 把預制物件 歸屬于那個父節點 表明嗎?轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/51930.html
標籤:Cocos2d-x
