1
votes

I am new to AS3 so please forgive me for asking something which is probably pretty straightforward to solve.

I am trying to load an image onto the stage using an external AS3 class. I'm not sure if this is the best way to do it but I started off with a tutorial so was following that.

My object (movieclip) has the class 'Mountain' and is called 'Mountain_mc'.

My external AS3 class file is called 'Mountain' and this is the code (it is stored at the same level of project folder as the Flash file which I am trying to load the image on to the stage) -

package 
{
    import flash.display.MovieClip;
    import flash.display.Stage;

    public class Mountain extends MovieClip
    {
        public function Mountain()
        {

            var myMountain:Mountain = new Mountain();
            stage.addChild(myMountain);
            myMountain.x = stage.stageWidth/2;
            myMountain.y = stage.stageHeight/2;
            trace ("I am a mountain");

        }
    }       
}

I am not getting any Errors, but also the trace command isn't working and my image doesn't appear on the stage. Any help would be very gratefully received. I have spent far too long trying to figure this out and I am getting nowhere.

Thanks!

1

1 Answers

5
votes

You should try to read more about what a class does, for starters. You have several mistakes in your code:

  1. You're actually doing a stack overflow there. Which is funny, because of the name of this site. :)

    You are recursively defining a variable of the same type as the parent. When you create the first myMountain, it will call it's constructor. Within it, it will create a variable myMountain which will also call it's constructor. And so on.

    Thus, no line of code below var myMountain:Mountain = new Mountain(); will show up. If you want, you can try to move the trace before that line. If you compile that, you will get an endless number of "I am a mountain".

  2. You cannot call the stage if your class is not added to stage.
  3. An instance of a class cannot add itself to stage.
  4. You must separate the code into code in your class and the code in your first keyframe.

Considering you have an empty movie, with a library symbol called "mountain_mc", which points to a class called Mountain, you must have an external file Mountain.as in the folder of your movie. You then have two types of code

on the first frame of your movie, you open the Actions panel and you write:

var myMountain:Mountain = new Mountain();
this.addChild(myMountain);
myMountain.x = stage.stageWidth/2;
myMountain.y = stage.stageHeight/2;

in your external file, Mountain.as, you have:

package {
    import flash.display.MovieClip;
    import flash.display.Stage;
    public class Mountain extends MovieClip
    {
        public function Mountain()
        {
            trace ("I am a mountain");
            // do something else
        }
    }
}