0

In SpriteBuilder, i want to use a global variable to change the characteristic of Sprite. Below is a simplified version of the code:

In Grid.h

#import "CCNodeColor.h"

extern int a;

@interface Grid : CCNodeColor
@property (nonatomic, assign) NSInteger score;

@end

In Grid.m

#import "Grid.h"

@implementation Grid{
    NSMutableArray *_gridArray;
    NSNull *_noTile;  
  }

- (void)mergeTileAtIndex:(NSInteger)x y:(NSInteger)y withTileAtIndex:(NSInteger)xOtherTile y:(NSInteger)yOtherTile {
Tile* mergedTile = _gridArray[x][y];
Tile* otherTile = _gridArray[xOtherTile][yOtherTile];
self.score += mergedTile.value + otherTile.value;
otherTile.value *= 2;   
_gridArray[x][y] = _noTile;
switch(otherTile.value)
  {
    case 2:
        a = 2;
        break;
    case 4:
        a = 4;
        break;
    case 8:
        a = 8;
        break;
  }
}

@end

In MainScene.m

#import "MainScene.h"
#import "Grid.h"

int a;

@implementation MainScene{
CCSprite *_red;
CCSprite *_green;
CCSprite *_blue;
}

- (void)didLoadFromCCB {
[self showTile];
}

-(void) showTile {
if (a == 2)
    _red.visible = TRUE;
else if (a == 4)
    _green.visible = TRUE;
else
    _blue.visible = TRUE;
}

@end

I can switch the case in Grid.m but i can't transfer the global variable to MainScene.m. Why? How do i make the code work? Do i need to put return in the switch statement?

  • 1
    Don't use global vars like that. Instead in MainScene get the node in questions (ie _theGrid = (Grid*)[self getChildByName:@"grid" recursive:YES]) and store it in an ivar like __weak Grid* _theGrid. Then you can do switch (_grid.score) if you expose the value as property. Much better design – CodeSmile May 14 '14 at 12:44
  • `otherTile` is declared but not initialized so I'm having trouble understanding how `otherTile.value *= 2;` gets you anything useful. – Phillip Mills May 14 '14 at 12:55
  • In Obj.C/iphone development, global variables are not really required...and good to avoid globals. – Guru May 14 '14 at 13:36

0 Answers0