AS3 - 如何从单独的类访问对象实例

时间:2012-07-23 22:14:11

标签: actionscript-3 flash flash-cs5 flashdevelop

我有一个游戏引擎类,可以在游戏加载时创建我的主角色实例和游戏边框实例:

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.

1 个答案:

答案 0 :(得分: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实例传递给constuctor的情况下执行此操作,而只需添加一个设置此属性的方法。

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>