2013-07-24 38 views
0

我得到錯誤:null對象引用的方法。我很困惑,不知道什麼是真正的原因。
所以我在舞臺上有一個「player_mc」實例的播放器movieClip,它將通過我的Document類傳遞到Player類中。
Player.as從另一個類調用一個類的movieclip,錯誤#1009

import flash.display.*; 
import flash.events.*; 


public class Player extends MovieClip 
{ 
    public var myPlayer:MovieClip; 

    public function Player(player:MovieClip) 
    { 
     myPlayer = player; 

     addEventListener(Event.ENTER_FRAME,on_enter); 
    } 

Document.as

import flash.display.*; 
import Components.Player.Player; 

public class Game_Main extends MovieClip 
{ 

    public var player:Player; 


    public function Game_Main() 
    { 
     player = new Player(player_mc); 


    } 

} 

現在在這裏,我認爲是問題的來源。我有一個基地級敵人舞臺上的green_enemy movieclip。
Enemy.as

import flash.display.MovieClip; 
import Components.Player.Player; 
import flash.events.Event; 

public class Enemy extends MovieClip 
{ 
    var theplayer:Player; 


    public function Enemy() 
    { 

     this.addEventListener(Event.ENTER_FRAME,on_enter); 
    } 

    public function on_enter(e:Event):void 
    { 
     if (this.hitTestObject(theplayer.myPlayer)) //calls player_mc from Player class 
     { 
      trace("hi"); 
     } 


    } 



} 

我喜歡對敵人的功能做的就是當敵人「player_mc」(這是在舞臺上),它會做一些碰撞。也許我的代碼是錯誤的。
任何幫助/技巧將不勝感激。謝謝!

回答

0

在你Enemy.as我看到

var theplayer:Player; 

未初始化。它是私人的,所以你不能從外面定義它。這意味着,除了來自這裏

this.hitTestObject(theplayer.myPlayer) 

您正在試圖調用myPlayer

嘗試在構造敵人類時定義此變量。


爲了防止空例外您可以檢查是否theplayer是空

public function on_enter(e:Event):void 
{ 
    if (theplayer && this.hitTestObject(theplayer.myPlayer)) 
    { 
     trace("hi"); 
    } 
} 
+0

我知道這很愚蠢,但你能告訴我你是什麼意思嗎?我最近剛剛進展到as3,所以很抱歉沒有成爲愚蠢的人。 –

+0

沒有道歉。更改'var theplayer:Player;'到'public var theplayer:Player;'就像John Dodson說的那樣。別忘了定義green_enemy.theplayer = yourPlayer。另見我的更新回答 – ZuzEL

+0

好吧!感謝你們。 –

0

要展開什麼ZuyEL說,你的變量是不是在你的敵人類全局定義的,因爲你只是添加你的敵人功能內的變種。相反,請執行以下操作:

public var thePlayer:Player; 

在敵人類之前,在敵人函數之前寫入以上內容。現在它已經供全班使用,稍後再調用它時不再爲空。