Storing Variables Across Play
I am having an issue with player.variables. It doesnt exist. What is the correct way to access
import * as hz from 'horizon/core';
class Mob extends hz.Component<typeof Mob> {
static propsDefinition = {
maxHealth: { type: hz.PropTypes.Number, default: 10 },
xpReward: { type: hz.PropTypes.Number, default: 50 },
};
private health!: number;
start() {
this.health = this.props.maxHealth;
}
takeDamage(amount: number, player: hz.Player) {
this.health -= amount;
console.log(`Mob took ${amount} damage! Health left: ${this.health}`);
if (this.health <= 0) {
this.onDefeated(player);
}
}
onDefeated(player: hz.Player) {
console.log(`Mob defeated! Awarding ${this.props.xpReward} XP to ${player.name.get()}`);
// :white_heavy_check_mark: Retrieve current XP from player variables
let currentXP = player.variables.get("playerXP") || 0;
let newXP = currentXP + this.props.xpReward;
// :white_heavy_check_mark: Store updated XP in player variables
player.variables.set("playerXP", newXP);
console.log(`${player.name.get()} now has ${newXP} XP`);
// :white_heavy_check_mark: Respawn mob after 5 seconds
this.async.setTimeout(() => {
this.health = this.props.maxHealth;
console.log(`Mob respawned!`);
}, 5000);
}
}
hz.Component.register(Mob);
the persistent variable? And if you have any documentation links, I would love to look through those! Thanks!
Take a look at the PPV section in the community manual. Once this link loads, you might need to click on the URL and hit enter again to take you to the correct section.
https://developers.meta.com/horizon-worlds/learn/documentation/mhcp-program/community-tutorials/creator-manual#player-persistent-variables-ppvs
In your example, try replacing it with this line where MyWorld is your PPV group. It looks like copilot still tries to auto-complete to the formatting you used, but it doesn't align with what is available currently from horizon/core.this.world.persistentStorage.setPlayerVariable(player, 'MyWorld:playerXP',newXP);