Skip to main content

Image gallery

A picture frame with Previous and Next buttons. Everyone sees the same picture, and the frame takes each picture's shape.

  • The frame is a quad with an unlit material, an ST Image Loader whose Target Renderer is the quad, and ImageGallery with the picture links in Urls.
  • The buttons are UI Buttons whose On Click calls Previous and Next.
  • Only the picture's number is synced. Pressing a button takes ownership and changes it; every device loads that picture itself in OnDeserialization. Pressing quickly only loads the last picture.
  • The loader keeps one picture and frees the one before, so the gallery can hold any number of links. Pictures seen in the last hour come back from the device's cache at once.

The pictures are Lorem Picsum photos from Unsplash.

ImageGallery.cs
using StageTime.SDK;
using TMPro;
using UnityEngine;

/// <summary>
/// A picture frame everyone sees the same picture in. Previous and Next buttons step through Urls; only the picture's
/// number is synced, and each device loads that picture with the ST Image Loader on this object. The frame takes the
/// picture's shape, at most Max Width x Max Height.
/// Put it on a quad with an ST Image Loader (Target Renderer: the quad) and hook Previous and Next to Buttons' On Click.
/// </summary>
public class ImageGallery : StageTimeBehaviour
{
public string[] urls;
public TMP_Text caption;
public float maxWidth = 2.4f;
public float maxHeight = 1.6f;

[Synced] private int index;

private STImageLoader loader;
private int shown = -1;

private void Start()
{
loader = GetComponent<STImageLoader>();
Show();
}

public void Next()
{
Step(1);
}

public void Previous()
{
Step(-1);
}

public override void OnDeserialization()
{
Show();
}

public override void OnImageLoadSuccess()
{
float aspect = (float)loader.width / loader.height;
float w = maxWidth;
float h = maxWidth / aspect;
if (h > maxHeight)
{
h = maxHeight;
w = h * aspect;
}
transform.localScale = new Vector3(w, h, 1f);
caption.text = (index + 1) + " / " + urls.Length;
}

public override void OnImageLoadError()
{
caption.text = "Picture " + (index + 1) + " could not load";
}

private void Step(int by)
{
if (urls.Length == 0) return;
Networking.SetOwner(Networking.LocalPlayer, gameObject);
index = (index + by + urls.Length) % urls.Length;
Show();
}

// Loads the synced picture unless it is already shown or loading.
private void Show()
{
if (loader == null || urls.Length == 0 || index == shown) return;
shown = index;
caption.text = "Loading " + (index + 1) + " / " + urls.Length + "...";
loader.LoadUrl(urls[index]);
}
}