同时对多个实例执行操作的最佳方法是什么?
假设我有50个名为A1到A50的动画片段实例,我想要只运行A20到A35的动作。
例如:
(A20-A35).gotoAndStop(2)
答案 0 :(得分:0)
您需要一个名为 loop 的算法操作。你不能抽象地一起解决一串中的事情,但你可以逐个循环并迭代这些产生基本相同的结果。请阅读:https://en.wikipedia.org/wiki/Control_flow#Loops当您需要执行大量类似操作时,它始终是循环。
关于你的问题:
// 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的想法,如果您确定所有这些都存在且所有这些都是 MovieClip ,那么您可以选择更短的版本:
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(...)始终返回具有给定名称的 DisplayObject (如果未找到,则返回null)。方括号运算符返回当前对象的无类型OOP字段。
它不适用于动态添加的子项(除非您将其引用传递给相应的字段)。
如果&#34;自动声明舞台实例&#34;它将无效。发布选项已关闭。
最后,这[&#34; A&#34; + 1] 和 A1 不完全相同,因为后者可以引用本地方法变量而不是对象成员。
我并不是说方括号是邪恶的,它们一样好,但是,一如既往,编程不是一个魔法,因此理解你在做什么是关键