![](/img/trans.png)
[英]AS3 - Error #1009: Cannot access a property or method of a null object reference
[英]AS3 / Flash - Error #1009: Cannot access a property or method of a null object reference
我知道這是一個常見的問題,但是我仔細研究了所有其他問題,無法解決我的問題。
我已經調試並找到了令人反感的代碼行,但是我不確定它到底是什么問題或如何解決。
下面的代碼-當“ enemy.movement();”時拋出該錯誤 調用“敵人”類中的運動函數。 代碼的前兩行(var xDist和var yDist)或經過專門標記。
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
public class zombiestandoffMain extends MovieClip
{
static public var enemy:Enemy;
static public var player:Player;
public var gameTimer:Timer;
public var crosshair:Crosshair;
public var army:Array;
public function zombiestandoffMain()
{
//enemy = new Enemy();
//addChild( enemy );
army = new Array();
var newEnemy = new Enemy;
army.push( newEnemy );
addChild( newEnemy );
player = new Player();
addChild( player );
crosshair = new Crosshair();
addChild( crosshair );
crosshair.x = mouseX;
crosshair.y = mouseY;
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}
public function onTick( timerEvent:TimerEvent ):void
{
var newEnemy:Enemy = new Enemy;
army.push( newEnemy );
addChild( newEnemy );
crosshair.x = mouseX;
crosshair.y = mouseY;
for each ( var enemy:Enemy in army ) {
enemy.movement();
}
//if ( player.hitTestObject( enemy ) )
//{
//}
}
}
}
和敵人階級:
package
{
import flash.display.MovieClip;
import flash.geom.Point;
import flash.events.Event;
public class Enemy extends MovieClip
{
public var sideSpawn = int(Math.random() * 3)
public function Enemy()
{
if (sideSpawn == 0) {//top
x = Math.random() * 800;
y = 200;
} else if (sideSpawn == 1) {//left
x = -20;
y = (Math.floor(Math.random() * (1 + 800 - 200)) + 200);
} else if (sideSpawn == 2) {//right
x = 800 + 20;
y = (Math.floor(Math.random() * (1 + 800 - 200)) + 200);
} else { //bottom
x = Math.random() * 800;
y = 800 + 20;
//(Math.floor(Math.random() * (1 + high - low)) + low);
}
}
public function movement():void {
var xDist = Math.abs(zombiestandoffMain.enemy.x - zombiestandoffMain.player.x);
var yDist = Math.abs(zombiestandoffMain.enemy.y - zombiestandoffMain.player.y);
if (xDist > yDist) {
if (zombiestandoffMain.enemy.x > zombiestandoffMain.player.x)
zombiestandoffMain.enemy.x-=2;
else zombiestandoffMain.enemy.x+=2;
} else {
if (zombiestandoffMain.enemy.y > zombiestandoffMain.player.y)
zombiestandoffMain.enemy.y-=2;
else zombiestandoffMain.enemy.y+=2;
}
}
}
}
我最好的猜測是敵人的x和y坐標為空-但我嘗試為坐標插入值,但仍然收到相同的錯誤。
感謝您的任何幫助!
您只宣布了敵人,還必須對其進行定義。 將zombiestandoffMain
內部的enemy
設置為新的Enemy
對象:
enemy = new Enemy();
我猜想它是與您在Movement()方法中引用的zombiestandoffMain有關。 我在“敵人級”中看不到任何定義。 如果要在Flash環境中或某個地方手動定義它,請確保正確引用了此屬性(zombiestandoffMain)。 希望能有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.