Search code examples
actionscript-3flash-cs3

How to reference a variable from a class to a scene in ActionScript 3.0


I am creating a platformer in flash as3 and i want to pass the var Score for my score from Scene 1 to the next. However, I realized the best way to do this was to store the score inside a class, but I am having trouble referencing the variable inside the scenes. Please help. This is the code currently inside the class

package file_as{  
public class CS{  
    public function CS(){
        public var Score:Number = 0;
        }
    }
}

I tried to reference the score in scene in the frame containing my code my stating

CS.Score 

But that didn't work so I'm lost.


Solution

  • To access it by doing CS.Score you would need to make that property static.

    Static vars/methods belong to the class itself (CS in this case), if not static, they belong to instances of that class (eg var csInstance:CS = new CS(); csInstance.Score = 6;)

    Here is how to make it static:

    package file_as{ 
        public class CS{
            public static var Score:Number = 0;  
        }
    }
    

    As an aside, your current class code should be throwing an error, as you can't have the public/private keywords inside a function. Also, since you defined the var inside a function (the constructor in your case) it would only be available in that function. Notice how in my example above the var definition is at the class level.

    All this said, I believe that if you defined a score var on your main timeline, it should be available across different scenes.