Avatars
Updated
An avatar is the 3D body that represents a person in the world. Avatars gives scripts access to the signed-in account’s avatars: the catalogue the platform offers, the person’s own avatars, and the one currently selected for their profile. Use it to build an avatar picker in your scene, to show thumbnails in a menu, or to let people upload a model of their own.
Avatars is supplied by the app MIRA runs in, and some apps do not offer it. When it is not offered, the global is undefined, so every script that uses it starts with a check.
Before you start
Section titled “Before you start”- You know how to write
asyncfunctions and handle rejected promises withtryandcatch. - You can build a simple UI with buttons and labels. See UI.
Avatar references
Section titled “Avatar references”Each avatar in the catalogue has a ref, { source, id }, that names it in every call. source is 'system-avatars' (offered by the platform) or 'my-avatars' (the account’s own).
| Avatar field | What it is |
|---|---|
ref |
Its reference, { source, id }. |
name |
Its name. |
thumbnailUrl |
A picture of it, or null. |
modelUrl |
The URL of its model, or null. |
Methods
Section titled “Methods”Every method returns a promise.
| Method | Resolves |
|---|---|
list({ source, page, search? }) |
A page of avatars: items, page and lastPage. Pages start at 1. search filters by name. |
getDefault() |
The platform’s default avatar, or null. |
getSelected() |
The account’s current selection: { modelUrl }, the model the profile wears. |
select(ref) |
Choose an avatar for the profile; resolves the new selection. This updates the saved profile. |
create({ name, origin |
Create a personal avatar. originType is 'created' or 'uploaded'; glb and thumbnail are { name, bytes } files. Resolves the new avatar. |
update |
Change a personal avatar, for example { name: 'Explorer' }. Resolves the updated avatar. |
delete |
Delete a personal avatar. Resolves a receipt: deleted, the replacement the profile now uses if any, and profileStatus ('unchanged', 'replaced' or 'pending'). |
To retry a failed create with the same files, pass the same input object again; build a new object when you change what you send.
Errors
Section titled “Errors”| Code | Meaning |
|---|---|
avatar_ |
The account may not do this. |
avatar_ |
Something in the request is invalid. |
avatar_failed |
The avatar service failed. |
When the Behavior stops while a call is pending, the call rejects with an AbortError. A change that already reached the service may still be applied.
Examples
Section titled “Examples”1. Listing the catalogue
Section titled “1. Listing the catalogue”#pragma lifecycle(startup)
async function startup() { if (typeof Avatars === 'undefined') { log('Avatars are not offered here'); return; } const page = await Avatars.list({ source: 'system-avatars', page: 1 }); log(`Page ${page.page} of ${page.lastPage}:`, page.items.map((avatar) => avatar.name).join(', '));
const current = await Avatars.getSelected(); log('Currently wearing', current.modelUrl ?? 'the default');}Reads one page of the system avatar catalogue with Avatars.list and the avatar the visitor wears with Avatars.getSelected, checking first that the app offers avatars.
Read the log. The preview has no avatar service, so the script reports that avatars are not offered; in a world with accounts it lists the catalogue.
- The
typeofcheck keeps the script working in apps that do not offer avatars. listreturns one page;lastPagetells you how many there are.
Snippets
Section titled “Snippets”1. An avatar picker
Section titled “1. An avatar picker”#pragma lifecycle(startup)
// Scene: a UI Panel with three UI Buttons named "Avatar 1", "Avatar 2", "Avatar 3",// each with a Signal Emitter on 'avatar/pick', a "Next Page" UI Button with a// Signal Emitter on 'avatar/next', and a "Status" UI Label.let items = [];let page = 1;let lastPage = 1;let status;
async function loadPage() { const result = await Avatars.list({ source: 'system-avatars', page }); items = result.items; lastPage = result.lastPage; for (let i = 0; i < 3; i++) { const button = findEntity(`Avatar ${i + 1}`); button.visible = i < items.length; if (items[i]) button.getComponent(UIButtonComponent).setText(items[i].name); } status.setProps({ text: `Page ${page} of ${lastPage}` });}
async function startup() { status = findEntity('Status').getComponent(UILabelComponent); if (typeof Avatars === 'undefined') { status.setProps({ text: 'Avatars are not available' }); return; }
on('avatar/pick', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; const index = Number(findEntity(event.entityId).name.slice(-1)) - 1; const avatar = items[index]; if (!avatar) return; try { await Avatars.select(avatar.ref); status.setProps({ text: `Now wearing ${avatar.name}` }); } catch (error) { status.setProps({ text: `Could not select: ${error.code ?? error.message}` }); } });
on('avatar/next', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; page = page < lastPage ? page + 1 : 1; await loadPage(); });
await loadPage();}- All three avatar buttons share one signal;
event.entityIdtells which one was pressed. selecttakes the avatar’srefand updates the account’s profile.- The “Next Page” button wraps around after the last page.
2. Uploading a personal avatar
Section titled “2. Uploading a personal avatar”#pragma lifecycle(startup)
// Scene: a UI Button with a Signal Emitter on 'avatar/upload'.const MODEL_URL = 'https://example.com/models/robot.glb';
async function upload() { const buffer = await HttpRequest.get(MODEL_URL).arrayBuffer(); const input = { name: 'Robot', originType: 'uploaded', glb: { name: 'robot.glb', bytes: new Uint8Array(buffer) }, }; try { const avatar = await Avatars.create(input); log('Created', avatar.name); await Avatars.updatePersonal(avatar.ref, { name: 'Robot (mine)' }); } catch (error) { if (error.code === 'avatar_invalid_input') log('That file is not a valid avatar'); else if (error.code === 'avatar_forbidden') log('This account cannot create avatars'); else log('Upload failed:', error.code ?? error.message); }}
function startup() { if (typeof Avatars === 'undefined') return; on('avatar/upload', (event) => { if (event.eventType === EventType.UIButton.Press) upload(); });}createtakes the model as bytes, here downloaded withHttpRequest.- The new avatar’s
refis used straight away to rename it. - Each error code gets its own message.
3. Removing a personal avatar
Section titled “3. Removing a personal avatar”#pragma lifecycle(startup)
// Scene: a UI Button with a Signal Emitter on 'avatar/remove-first'.async function removeFirst() { const mine = await Avatars.list({ source: 'my-avatars', page: 1 }); const first = mine.items[0]; if (!first) { log('No personal avatars'); return; } const receipt = await Avatars.deletePersonal(first.ref); if (receipt.profileStatus === 'replaced') log('Your profile now uses another avatar'); if (receipt.profileStatus === 'pending') log('Deleted; your profile will update shortly');}
function startup() { if (typeof Avatars === 'undefined') return; on('avatar/remove-first', (event) => { if (event.eventType === EventType.UIButton.Press) removeFirst().catch((error) => log(error.code)); });}'my-avatars'lists only the account’s own avatars, which are the only ones you can delete.- The receipt’s
profileStatussays whether the profile had to switch to another avatar.
Common mistakes
Section titled “Common mistakes”- No
undefinedcheck. In apps without avatars,Avatars.list(...)throws becauseAvatarsisundefined. - Passing an id instead of a
ref.select,updatePersonalanddeletePersonaltake the wholeref,{ source, id }. - Deleting platform avatars. Only
'my-avatars'can be updated or deleted. - Changing the account without asking.
selectanddeletePersonalchange the saved profile.