ForumsProgramming ForumI need help with a silly AS coding issue

2 6138
Annihalation
offline
Annihalation
479 posts
Nomad

I'm currently in the middle of testing some AS code, and for some reason I can't get it to work. I have a button on the screen that, when pressed, runs a function to add a movie clip (lets call it an Orc) to the stage each time it is pressed. I also want the Orcs generated to work so that, when selected, a variable "PCSelect" will give the ID of which Orc is selected, and will move another movie clip to the selected Orc's position (lets call it a targeting Reticle). Here is the code I have so far:

function createOrc():Void {
Orc = _root.attachMovie("orc", "orc"+currentOrcID, unitDepth);
Orc._x = 200+random(200); //setting position of Orc
Orc._y = 150+random(150);
// random variables here
Orc.UID = currentOrcID;
unitDepth++;
currentOrcID++;

Orc.onEnterFrame = function() {
//frame based calculations
}
Orc.onRelease = function() {
if (OrderID == 0) {
//no Orders, select
reticle._x = Orc._x;
reticle._y = Orc._y;
PCSelect = Orc.UID;
//Select this orc code;
} else if (OrderID == 1) {
//move order
//insert move to code here
}
};


The bold area is what I cant seem to get to work. Instead of being able to select any orc on click, it selects ONLY the last orc created. So if there are 5 orcs, clicking on any of the 5 orcs always selects orc 5. Can anyone give me a tip to make each Orc have its own functions?
  • 2 Replies
Annihalation
offline
Annihalation
479 posts
Nomad

Figured it out myself, I just put the functions inside the movie clip so whenever they run they target that particular instance of the movie clip. Just in case anyone else has a similar problem, figured I would share that info.

arobegamr
offline
arobegamr
130 posts
Nomad

The reason your code is not working is because inside of your Orc.onRelease function, "Orc" will refer to the current value of the variable named "Orc" on the root clip (Which is reset to the newest instance each time you create a new one).

Change the word "Orc" inside of any function attached to the Orc instance (Orc.functionname), to "this". Example:

Orc.onPress = function() {
_root.currentOrc = this;
}

What it does: Sets a variable on the main stage to record the Orc that was clicked. (Resets on each click of course)

Showing 1-2 of 2