如何将变量传递给新孩子? [flash AS3]

时间:2013-02-12 00:51:51

标签: actionscript-3 class instance-variables addchild

代码很好地说明了问题,我已经削减了一切无关的内容。

游戏开始时创建2-4个亲属

function createInitialKinsmen()
{
    for (var k:int = 1; k < 3 + Math.round(Math.random() * 2; k++)
    {
        if (k == 1)
        {
            createKinsmen(0);
            trace ("player");
        }
        else
        {
            createKinsmen(1);
            trace ("starting kinsmen");
        }
    }
}

亲属创建功能

function createKinsmen(arrivalTypeVar:int)
{
    var newKinsmen = new kinsmen;
    listPanel.kinsmenDivider.addChild(newKinsmen);
    totalKinsmen++;
    totalKinsmenAlive++;
    newKinsmen.name = "kinsmen" + totalKinsmen;
    newKinsmen.arrivalType = arrivalTypeVar;
}

Kinsmen课程

public class kinsmen extends MovieClip
{
    var arrivalType:int;
    function kinsmen()
    {
        trace(this.name);
        if (this.arrivalType = 0)
        {
            trace("player");
        }
        if (this.arrivalType = 1)
        {
            trace("starting kinsmen");
        }
    }
}

输出应该说:

kinsmen1
player
player
kinsmen2
starting kinsmen
starting kinsmen
kinsmen3
starting kinsmen
starting kinsmen
kinsmen4
starting kinsmen
starting kinsmen

但反而说:

kinsmen1
player
player
kinsmen2
player
starting kinsmen
kinsmen3
player
starting kinsmen
kinsmen4
player
starting kinsmen

这意味着 arrivalType 变量未被传递。似乎是硬编码的变量可以通过,因此此刻我在kinsmen movieclip中有一个alpha 0的正方形,它的x位置决定了构造函数中 arrivalType 的值但是这肯定可以不是很好的做法,有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

我认为您只想修改kinsmen类的构造函数,以接受arrivalTypename的参数。

您目前正在做的是构建一个新的kinsmen对象,然后在该对象上设置arrivalTypename。因此,当构造函数代码运行时,arrivalTypeint的默认值,即0。

kinsmen类中修改你的构造函数:

function kinsmen(arrivalType:int, name:String)
{
    this.name = name;
    this.arrivalType = arrivalType;
    if (this.arrivalType == 0)
    {
        trace("player");
    }
    if (this.arrivalType == 1)
    {
        trace("starting kinsmen");
    }
}

修改您的createKinsmen()函数,以便将arrivalType的值传递给构造函数方法,而不是在对象之后设置arrivalTypename创建:

function createKinsmen(arrivalTypeVar:int)
{
    totalKinsmen++;
    totalKinsmenAlive++;
    var newKinsmen = new kinsmen(arrivalTypeVar, "kinsmen" + totalKinsmen);
    listPanel.kinsmenDivider.addChild(newKinsmen);
}