First, a class does not have a parent or child; an instance has a parent or child. It's a good idea to try to get used to thinking that way. When you make something static
you are making the code associated with the class, which is not specific to any particular instance. Meanwhile, methods like addChild
and removeChild
are instance functions, because they necessarily relate to specific instances of the class. So when you try to do things like expose a function globally by making it static
, but want to do instance specific things like removeChild
, you can get rather tangled.
To solve your problem, there are a few solutions.
You can simply "reach upward" to remove the child. For example, parent.removeChild(this)
will remove a child from its parent. If you know the parent is a MainClass
instance, you can cast and reference a property on it: parent.removeChild(MainClass(parent).start_icon)
. (start_icon
should not be static
.) You can even reach parent.parent.
and so on.
That's not a great solution, though, because you are making the code assume a certain parent/child hierarchy. If you move things around it will break at runtime. A better solution (already mentioned in the comments) is to use events. For example:
class MainClass extends Sprite {
public var startIcon:StartIcon = new StartIcon();
public function MainClass() {
addChild(startIcon);
addEventListener("removeStartIcon", removeStartIcon);
}
private function removeStartIcon(e:Event):void {
removeChild(startIcon);
}
}
// From start icon, or any child (or children's child, etc) of main class instance:
dispatchEvent(new Event("removeStartIcon", true)); // bubbles=true, to trickle up the display hierarchy
Lastly, you can use the singleton pattern. Like others, I don't recommend this, but it is a quick and easy way to make a single instance of a class behave globally. The gist is that you expose a static reference to a single instance of your class, with the assumption you only ever need a single instance of that class. Then you can reference instance functions and properties from anywhere through the static reference of the class to its single instance. For example:
class MainClass extends Sprite {
public static var main:MainClass;
public var startIcon:StartIcon = new StartIcon();
public function MainClass() {
main = this;
addChild(startIcon);
}
public function removeStartIcon():void {
removeChild(startIcon);
}
}
Now from anywhere you can do this: MainClass.main.removeStartIcon()
or even MainClass.main.removeChild(MainClass.main.startIcon)
.