global variables in AS3

后端 未结 1 1093
不知归路
不知归路 2021-01-16 08:03

Ok, I want to be able to access certain variables from anywhere within a Flash file or Flash files loaded by that Flash file. How do I do it? I don\'t know what classes are,

相关标签:
1条回答
  • 2021-01-16 09:00

    Well, there is no more _global like there was in as2 - and since you don't want to use classes you can't use static variables (I can explain these if you're interested). So you're left with using variables on the root. For example, you can define a variable on the main timeline like this:

    var myGlobal:Number = 100;
    

    If you want to access it elsewhere ... that is, on the timeline of other movieClips you need to say:

    MovieClip(root).myGlobal;
    

    Which if you've never seen before probably looks absurd. Basically we are casting the root to a movieClip to give us access to its dynamic properties. Luckily, you can set it up so you don't have to keep writing MovieClip(root) all the time:

    // do this on any movieClip where you want to access globals
    var global:MovieClip = MovieClip(root);
    
    trace(global.myGlobal);
    

    So in the end its just one extra line of code to get the functionality back to the way it was in AS2.

    Edit

    1. go to main timeline and add this to your actions: var myGlobal:Number = 100;
    2. make a new movieClip make sure its on the stage
    3. go into the new movieClip and add this to your actions :

      var global:MovieClip = MovieClip(root); trace(global.myGlobal);

    4. test your movie

    0 讨论(0)
提交回复
热议问题