actionscript-3stringswitch-statement

Problem with actionscript switch not execute first case


My problem is that I can't (don't know) make work my switch. Here in my first case, I input "hache", and it doesn't pass through. Strangely, in my trace(traget); [Object hache] or [Object extincteur] (depending on which mc I click on) comes out... Why doesn't it go through the first case? I have no clue. I tried removing the " ".

package cem
{
    import flash.display.MovieClip;

    public class actionObjets{
        
        /*--inventaire--*/
        private static var inventaireHache:Boolean = false;
        private static var inventaireExtincteur:Boolean = false;
        
        private var objetClique:MovieClip;

        public function actionObjets(target) {
            this.objetClique = target;
            switch(objetClique){
                case "hache":
                    inventaireHache = true;
                    ajouterInventaire(objetClique);
                    break;
                case "extincteur":
                    inventaireExtincteur = true;
                    ajouterInventaire(objetClique);
                    break;
            }
            trace(target);
        }
        private function ajouterInventaire(objetEnlever):void{
            objetClique.parent.removeChild(objetClique);
            trace(inventaireHache + " - Hache");
            trace(inventaireExtincteur + " - Extincteur");
        }
        
    }
    
}

by the way, target is the movieClip I clicked on a.k.a. Object extincteur, or Object hache.


Solution

  • The problem is that objetClique isn't a string. You probably want to do something like switch (objetClique.name).

    If you want to understand what's going on, rewrite the code this way:

    if (objetClique == "hache") {
      // ...
    } else if (objetClique == "extincteur") {
      // ...
    }
    

    I hope this illustrates more clearly why the switch doesn't work. objetClique couldn't be equal to the string "hache", because it's not a string. From the looks of it objetClique refers to a DisplayObject and they have a property called name, which is what you want to compare:

    if (objetClique.name == "hache") {
      // ...
    } else if (objetClique.name == "extincteur") {
      // ...
    }
    

    that code would work, and it's equivalent to a switch that looks like this:

    switch (objetClique.name) {
      case "hache":
        // ...
        break;
      case "extincteur":
        // ...
        break;
     }