具有实例列表的操作 - AS3

Actions with a list of instances - AS3

同时对多个实例执行操作的最佳方法是什么?

假设我有 50 个名为 A1 到 A50 的动画片段实例,我想 运行 一个只有 A20 到 A35 的动作。

例如:

(A20-A35).gotoAndStop(2)

您需要一个名为 loop 的算法操作。您无法一次 抽象地解决一堆问题,但您可以一个接一个地循环和迭代这些问题,从而产生基本相同的结果。请阅读以下内容:https://en.wikipedia.org/wiki/Control_flow#Loops 当您需要执行大量类似操作时,它总是 loop

关于您的问题:

// Loop iterator from 20 to 35 inclusive.
for (var i:int = 20; i <= 35; i++)
{
    trace("");

    // Compose the name of the MovieClip to retrieve.
    var aName:String = "A" + i;

    trace("Retrieving the MovieClip by name", aName);

    // Retrieve the instance by its instance name.
    var aChild:DisplayObject = getChildByName(aName);

    // Sanity checks about what exactly did you find by that name.
    if (aChild == null)
    {
        // Report the essence of the failure.
        trace("Child", aName, "is not found.");

        // Nothing to do here anymore, go for the next i.
        continue;
    }
    else if (aChild is MovieClip)
    {
        // Everything is fine.
    }
    else
    {
        // Report the essence of the failure.
        trace("Child", aName, "is not a MovieClip");

        // Nothing to do here anymore, go for the next i.
        continue;
    }

    // Type-casting: tell the compiler that the child is actually
    // a MovieClip because DisplayObject doesn't have gotoAndStop(...)
    // method so you will get a compile-time error even if you are
    // sure the actual object is a valid MovieClip and definitely has
    // the said method. Compile-time errors save us a lot of pain
    // we would get from run-rime errors otherwise, so treasure it.
    var aClip:MovieClip = aChild as MovieClip;

    trace(aClip, "is a MovieClip and has", aClip.totalFrames, "frames.");

    if (aClip.totalFrames < 2)
    {
        // Nothing to do here anymore, go for the next i.
        continue;
    }

    // Now you can work with it.
    aClip.gotoAndStop(2);
}

现在你已经一步步理解了 while 的想法,如果你确定它们都存在并且它们都是 MovieClips 你可以选择一个更短的版本:

for (var i:int = 20; i <= 35; i++)
{
    (getChildByName("A" + i) as MovieClip).gotoAndStop(2);
}

UPD:您也可以使用方括号访问运算符来处理子项。

for (var i:int = 20; i <= 35; i++)
{
    // You can skip type-casting as this["A" + i] returns an untyped reference.
    this["A" + i].gotoAndStop(2);
}

但也存在差异和并发症。方法 getChildByName(...) 始终 returns 具有给定名称的 DisplayObject(如果找到 none 则为 null) .方括号运算符 returns 当前对象的非类型化 OOP 字段。

它不适用于动态添加的子项(除非您将它们的引用传递给相应的字段)。

如果 "Automatically Declare Stage Instances" 发布选项关闭,它将无法工作。

最后,this["A" + 1]A1不完全一样,因为后者可以参考局部方法变量而不是对象成员。

我并不是说方括号是邪恶的,它们一样好,但是,一如既往,编程不是魔术,因此 了解你在做什么 是关键。