0

我有一个游戏引擎类,它在游戏加载时创建我的主角实例和游戏边框实例,如下所示:

public class Engine extends MovieClip
{
     var char:Char = new Char(stage);
     stage.addChildAt(char, 1);

     var border1:Border = new Border();
     stage.addChild(border1);

    }

我想访问在我的 Char 类的 Engine 类中创建的变量border1。这可能吗,如果可以,我该怎么做?

我试过改变代码,所以border1是静态的,就像这样

static var border1:Border = new Border();

但后来我得到

error 1012: The static attribute may be used only on definitions inside a class.
4

1 回答 1

0

你可以通过几种方式做到这一点。

1.  Create the border1 and char instances in reverse order and pass the border1 to the char instance to maintain a reference.

var border1:Border = new Border();
stage.addChild(border1);

var char:Char = new Char(stage, border1);
stage.addChildAt(char, 1);

// Char consructor

public function Char(target:DisplayObjectContainter, border:Border):void {
    ...
    this._border = border;
}

// Now you have a reference to the border1 instance within your char instance.

您也可以在不将border1 实例传递给构造函数的情况下执行此操作,而只需添加一个设置此属性的方法。

public function setBorder(border:Border):void {
    this._border = border;
}

// OR

public function set border(border:Border):void {
    this._border = border;
}

另一种选择是让 Engine 实例保持对边界的引用并允许通过 Engine 实例进行通信。例如,

public class Engine extends MovieClip {

    public var char:Char;
    public var border1:Border;

    public function Engine():void {
        char = new Char(stage);
        stage.addChildAt(char, 1);

        border1 = new Border();
        stage.addChild(border1);
    }

现在,如果 char 实例有对引擎实例的引用,那么边界实例可以被myEngineInstance.border1.

或者您可以将边框实例设为静态。将其设为静态将允许 Char 实例内部的代码,例如:

Engine.border1.<whatever>
于 2012-07-23T22:27:59.603 回答