开发者

Help loading a texture in a variable in Objective-C

I have a "ball" sprite that changes it's texture开发者_JAVA技巧 when a certain scenario occurs. I change it's texture like this:

[ball setTexture:[[CCTextureCache sharedTextureCache] addImage:@"red.png"]];

This does work; it changes the ball sprite to use the red.png image. How would I handle this if I have about 20 balls that need to switch to using this sprite? Would I run through each ball and "addImage"?

If I could, I would like to load the texture once, save it in a variable (called like "redTexture"), and then be able to assign it to any of the ball objects.

Any advice on how to approach this would be a huge help, thank you!


If you were to put that statement inside, say, a for loop, you'd be adding the red.png image to the shared texture cache over and over again, which I doubt is what you want.

Let's back up and re-write things a bit, starting by adding the red.png image to the shared texture cache, on a line by itself:

[[CCTextureCache sharedTextureCache] addImage:@"red.png"];

You'd subsequently get the same texture again simply by calling [CCTextureCache sharedTextureCache]. Until you add another image to the shared texture cache, that is.

CCTextureCache is a singleton, and its docs don't suggest there's a way to make a copy of the shared texture cache (which would be ideal for preserving your redTexture). That being the case, just create a variable and point it at [CCTextureCache sharedTextureCache]; just be careful not to add any other images to it before you're done with it:

CCTextureCache *redTexture = [CCTextureCache sharedTextureCache];

Now let's assume you already have an array (or mutable array) called ballArray, that contains 20 ball objects. You could loop through them like this:

for (YourBallObject *ball in ballArray)
{
    [ball setTexture:redTexture];
}

Or even better, you could do this:

[ballArray makeObjectsPerformSelector:@selector(setTexture:) withObject:redTexture];

Good luck in your endeavors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜