Shared objects are the core feature of p5.party. The property values of a shared object are automatically kept in sync over the network, allowing you to easily share state and data to everyone interacting with your sketch. A shared object's properties can be booleans, strings, numbers, arrays, and even nested data objects.
After you call partyConnect()
you can load a shared object with partyLoadShared()
. The shared object will be kept in sync across instances of your sketch.
You can have multiple shared objects, but each needs a unique name
. You can name your shared objects anything you want, but must follow the javascript variable name rules (start with a letter, use only letters, numbers, and underscores). Names like globals
, locations
, my_data
would all work. In this example, the object is named globals
on the server, and stored in a variable called shared
on the client.
Creating a shared object is asynchronous; you can’t use the returned shared object right away. Instead, call partyLoadShared
from preload()
and p5 will wait until the shared object is fully loaded and ready to use before calling setup()
or draw()
. You can also use a callback to be notified when the shared object is ready.
let shared;
function preload() {
partyConnect(
"wss://demoserver.p5party.org",
"click_history"
);
shared = partyLoadShared("globals");
}
It's a good idea to initialize your shared object by setting initial values for all the properties you plan to use.
You can do this by providing an object literal when you loaded the shared object. The properties in the object literal will be copied into the shared object ONLY IF the object currently has no properties:
let shared;
function preload() {
partyConnect(...);
shared = partyLoadShared("globals", {x: 0, y: 0});
}
You might want to set the values on the shared object when the first client connects to the room, OVERWRITING any values that might have been there from a previous game:
function setup() {
if (partyIsHost()) {
partySetShared(shared, {x: 0, y: 0});
}
}
Or if you want to reset the shared object every time a client connects, even if other clients are already connected you might do something like this:
function setup() {
partySetShared(shared, {x: 0, y: 0});
}
You set properties on a shared object just like any other Javascript object, using dot notation: shared.x = 10;
p5.party watches the shared object for you and sends your changes to server—and all the other instances of your sketch—automatically.
function mousePressed(e) {
// write shared data
shared.x = mouseX;
shared.y = mouseY;
}
Alternately, you can replace all the properties of a shared object at once using partySetShared()
.