【问题标题】:AS3 reference movieclip by .name property.name 属性的 AS3 参考影片剪辑
【发布时间】:2012-07-25 07:53:22
【问题描述】:

是的,另一个简单的 noobie as3 问题。

如何通过“.name”引用影片剪辑?

我尝试寻找解决方案,但找不到任何东西。基本上,我使用循环将一组电影剪辑添加到舞台,所以我发现区分它们的方法是给它们一个“某物”的 .name + 循环的“i”。所以现在它们被命名为“something1”、“something2”、“something3”等等。

现在,我需要将一些发送到特定框架。通常我会这样做:

something1.gotoAndStop(2);

但是“something1”不是实例名称,只是“.name”。我找不到引用它的方法。

【问题讨论】:

    标签: actionscript-3 flash movieclip


    【解决方案1】:

    你想使用 getChildByName("name") more info

    导入 flash.display.MovieClip;

    // create boxes
    for(var i:int = 0 ; i < 4; i++){
    
        var box:MovieClip = new myBox(); // myBox is a symbol in the library (export for actionscript is checked and class name is myBox
    
        box.name = "box_" + i;
        box.x = i * 100;
        this.addChild(box);
    
    }
    
    // call one of the boxes
    
    var targetBox:MovieClip = this.getChildByName("box_2") as MovieClip;
    targetBox.gotoAndStop(2);
    

    【讨论】:

    • 每当我使用 getChildByName("something1");我收到“标签必须是简单标识符”错误。
    • 好的,我添加了上面的代码并测试了它。应该可以正常工作。
    【解决方案2】:

    按名称访问事物很容易出错。如果你是新手,这不是一个好习惯。我认为更安全的方法是存储对您在循环中创建的事物的引用,例如在数组中,并通过它们的索引引用它们。

    例子:

    var boxes:Array = [];
    const NUM_BOXES:int = 4;
    const SPACING:int = 100;
    
    // create boxes
    for(var i:int = 0 ; i < NUM_BOXES:; i++){
    
        var box:MovieClip = new MovieClip(); 
    
        // You can still do this, but only as a label, don't rely on it for finding the box later!
        box.name = "box_" + i; 
        box.x = i * SPACING;
        addChild(box);
    
        // store the box for lookup later.
        boxes.push(box); // or boxes[i] = box;
    }
    
    // talk to the third box
    const RESET_FRAME:int = 2;
    var targetBox:MovieClip = boxes[2] as MovieClip;
    targetBox.gotoAndStop(RESET_FRAME);
    

    注意,我还用常量和变量替换了许多松散的数字,这也将有助于您的编译器发现错误。

    【讨论】:

    • 感谢您的有用建议!
    【解决方案3】:

    您可以使用父级按名称获取子级。如果父级是舞台:

    var something1:MovieClip = stage.getChildByName("something1");
    something1.gotoAndStop(2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 2017-06-24
      • 2013-12-22
      相关资源
      最近更新 更多