Below is a MXML code built from Flash Builder 4.5 with AIR SDK 3.0. Using Starling framework to create 2D animation and wonder how do I call a addText
function without create a new instance of Game
?
main.mxml is a main application:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="ht开发者_JAVA百科tp://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
applicationComplete="windowedapplication1_applicationCompleteHandler(event)"
backgroundAlpha="0" showStatusBar="false" height="700" frameRate="60" width="800">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import starling.core.Starling;
private var mStarling:Starling;
protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
this.y=0;
mStarling = new Starling(Game, stage);
mStarling.start();
}
private function gaa():void {
//How to access addText() in Games.as?
}
]]>
</fx:Script>
<s:Button x="693" y="19" label="Add Text" click="gaa()"/>
</s:WindowedApplication>
Games.as is a package that create sprite:
package
{
import scenes.Scene;
import starling.display.Button;
import starling.display.Image;
import starling.display.Sprite;
import starling.events.Event;
import starling.textures.Texture;
public class Game extends Sprite
{
private var mMainMenu:Sprite;
private var mCurrentScene:Scene;
public function Game()
{
var bg:Image = new Image(Assets.getTexture("Background"));
addChild(bg);
mMainMenu = new Sprite(); //create new sprite
addChild(mMainMenu);
}
public function addText():void {
var logo:Image = new Image(Assets.getTexture("Logo")); //add logo
logo.x = int((300 - logo.width) / 2);
logo.y = 50;
mMainMenu.addChild(logo);
}
}
}
how do I call a addText function without create a new instance of Game?
You need to use static methods to call a method on a class without creating an instance of it. Something like this:
public static function addText():void {
var logo:Image = new Image(Assets.getTexture("Logo")); //add logo
logo.x = int((300 - logo.width) / 2);
logo.y = 50;
mMainMenu.addChild(logo);
}
Then you can call the method like this:
Games.addText()
Of course, the method, as written, will throw an error; because mMainMenu
is not defined in the method. You won't be able to access instance variables on a class inside a static method.
精彩评论