Context
If you have a value in a Sprite which is also needed in a very nested Sprite, you need to add that prop to all of the intermediate Sprites.
Context avoids this by setting up a context value which can be accessed by any nested Sprite, without having to manually pass through props.
This can be especially useful for 'global' props you need in many Sprites in your game - e.g. player controller settings or the login state of an online game.
Context is very much inspired by React Context and works the same way, but the API is slightly different.
You can create a Context with the makeContext
function:
- JavaScript
- TypeScript
You then return a context.Sprite
where you want to set this context. Only the Sprites in the sprites
prop have access to the context:
- JavaScript
- TypeScript
The Context value can be read in nested Sprites using the getContext
Sprite method:
- JavaScript
- TypeScript
You can pass any values you want into the context
prop. You can even pass in state with callbacks for your nested Sprites:
- JavaScript
- TypeScript