How to use setTag and getTag

Dear All,

I am new at cocos 2d-x and I am developing a memory card game.
My idea is create the cards as ItemToggle, and I trying to identify each “face” of the card the user have touched.
But the getTag is not getting the value that I have set

Can someone help me?
than you in advance

CCMenuItem ***carta_frente = CCMenuItemImage::create;
*carta_frente~~>setTag;
CCMenuItem **carta_figura = CCMenuItemImage::create;
*carta_figura~~>setTag;
*carta_1 = CCMenuItemToggle::createWithTarget,*carta_frente,_carta_figura,NULL);
pMenu_carta[2] = CCMenu::create;
pMenu_carta[2]>setPosition;
pMenu_carta[2]
>setScale;
this~~>addChild;
pMenu_carta[2]~~>setVisible;

void MenuPrincipal::ClickouCarta {
CCMenuItem** pMenuItem = (CCMenuItem *)(pSender);
int tag = (int)pMenuItem->getTag();

switch (tag)
{
case 111:
case 222:
default: ;
// log error w/tag
}
}

Are you actually checking the tag value? Or are you simply relaying on your “switch(tag)” block for it? Because without “break” statements, it will always do the “default”, as it will “fall” to it.

Example :

switch(value) {

case 1 : someFun();
case 2 : someFun(); break;
default: someFun();

}

If the value is other than 1 or 2, someFun() will be called once (from the default block - `break` here is not needed as it is the lastt block). If the value is 2, someFun() will also be called only once, because there is a `break`. But if the value is 1, someFun() will be called twice, because it will enter the `case 1:` block, and after returning from someFun() it will “fall” to `case 2:` block, because there was no `break` in `case 1:` block.

So if you were to add breaks to your case 111 and case 222 you won’t get error logs for this tag values.


Side note, as I don’t know much about MenuItemToggle - are you sure that it is not the sender?

Hi Pawel, thank you for your answer.
I will include the “break” in the code.

I did check the Tag value using debug, it is “~~1".
When I set the Tag in variable _carta_frente, the Tag gets the new value, 111 or 222.
When the “ClickouCarta” is called, the “pMenuItem” has "~~1” as Tag.
So the issue is “passing the Tag”, before the switch statement.

There is other way to implement?
MenuItemToggle was the easiest way the I found however is not working.

BR

Are you sure that pMenuItem in callback function is not the MenuItemToggle? Could you try setting

_carta1->setTag(333);

and checking in the callback function if it is it?

I solved the issue adding the following code:

CCMenu * mainMenu = CCMenu::create();
mainMenu > setPosition;
this
> addChild( mainMenu );

And replacing “this~~>addChild;" by "mainMenu~~> addChild(pMenu_carta[2] )”

And I have the tag passed.
Thank you all.