Keeping a score
Score state that needs to be shared across multiple components is best managed using a Custom Context. A context exposes data and methods that any behavior or component in the scene can access:
@zContext()export class ScoreContext extends Context { score = 0;
increment(amount = 1) { this.score += amount; this.zcomponent.nodes.myScoreText.text = `Score: ${this.score}`; }
reset() { this.score = 0; this.zcomponent.nodes.myScoreText.text = `Score: ${this.score}`; }}Any behavior can then call into it:
this.zcomponent.contexts.ScoreContext.increment();Custom score Context and Behavior
Section titled “Custom score Context and Behavior”This tutorial will walk you through creating a score context and a button behavior that increments it.
This tutorial assumes that a text node and a button have already been added to the Hierarchy.
1. Click on your button in the Hierarchy and then find the Behaviors Panel. Click on the plus (+) icon in the Behaviors Panel and then + New Custom Behavior.

2. Give your custom behavior a name and then click on Create.

If you want your custom behavior to take effect in the Mattercraft editor, check the Run at Design Time box.
3. Head to the Left Menu and double click on your custom behavior to open it in the Mattercraft scripting environment.

You can also open the script by right clicking on it in the Left Menu and going to Open to the Side
4. Add a @zRegister method that calls increment() on your score context when the button is clicked:
@zRegister('onClick')private _handleClick() { this.zcomponent.contexts.ScoreContext.increment();}5. Your full score context and button behavior should look something like this:
import { Context, zContext } from '@zcomponent/core';import Scene from './Scene.zcomp';
@zContext()export class ScoreContext extends Context { protected zcomponent = this.getZComponentInstance(Scene);
score = 0;
increment(amount = 1) { this.score += amount; this.zcomponent.nodes.myScoreText.text = `Score: ${this.score}`; }
reset() { this.score = 0; this.zcomponent.nodes.myScoreText.text = `Score: ${this.score}`; }}import { Behavior, zBehavior, zRegister } from '@zcomponent/core';import { Button } from '@zcomponent/html/lib/button';import Scene from './Scene.zcomp';
@zBehavior({ icon: 'scoreboard' })export class ScoreButtonBehavior extends Behavior<Button> { protected zcomponent = this.getZComponentInstance(Scene);
@zRegister('onClick') private _handleClick() { this.zcomponent.contexts.ScoreContext.increment(); }}You may need to use
'onPointerDown'instead of'onClick', depending on the node you are using as a button.