#Custom Dynamic Property Definitions (default values and more)

1 messages · Page 1 of 1 (latest)

raw wolf
#

With the removal of dynamic property definitions, I found that default values used to be quite useful, so I wrote my own dynamic property APIs. This comes with a few useful features:

  • accessing properties through code - no more hardcoded strings
  • default values (of course)
  • optional setter callbacks, to have a function that will always run when setting the value of a property

Here's an example of how this implementation can be used:

for (const player of world.getAllPlayers()) {
    // get the DynamicProperty object for the player
    const money = DynamicProperties.Money.get(player);
    // change the value - the callback will run
    money.value = 100;
    // display the new value
    world.sendMessage(money.value);
}```

And this is how they are defined in JS:
```js
export const DynamicProperties = {
    Nickname: new DynamicPropertyDef("nickname", "Unknown"),
    HasEvolved: new DynamicPropertyDef("has_evolved", false),
    Money: new DynamicPropertyDef("fear", 0, x => Math.max(x, 0)), // example callback - the value cannot go below 0
};
#

Here's the JS code for them:

import { Entity } from "@minecraft/server";

/** Represents the dynamic property of an entity */
class DynamicProperty {
    constructor(id, entity, defaultValue, callback) {
        this.id = id;
        this.entity = entity;
        this.defaultValue = defaultValue;
        this.callback = callback;
    }
    get value() {
        const v = this.entity.getDynamicProperty(this.id);
        return (v !== undefined) ? v : this.defaultValue;
    }
    set value(value) {
        let v = value;
        if (this.callback) {
            v = this.callback(v, this.entity);
        }
        this.entity.setDynamicProperty(this.id, v);
    }
}
/** Represents the definiton of a dynamic property. */
class DynamicPropertyDef {
    /**
     * @param {String} id Identifier of the property
     * @param defaultValue The property's default value
     * @param callback Callback function that is run whenever the property is set
     */
    constructor(id, defaultValue, callback) {
        this.id = id;
        this.defaultValue = defaultValue;
        this.callback = callback;
    }
    /**
     * Returns the DynamicProperty object for a given entity.
     * @param {Entity} entity
     */
    get(entity) {
        return new DynamicProperty(this.id, entity, this.defaultValue, this.callback);
    }
}```
#

For the typescript fellas, the code is in the file below, along with the definitions

#

I wrote this in typescript, but also posted JS compiled version. In ts the code is written better and makes use of the language's generic types

elfin yew
#
entity.getDynamicProperty("some:property") ?? "default value";