Binding to File and Web URIs
Bindables provides a simple way to load images and audio clips from external files and web URLs.
These extension methods are available for any property or type Texture or AudioClip:
Tip
This sample is in the Bindables Package at: Samples/Scenes/08_BindToURI
#if UNITY_UI
using UnityEngine;
using UnityEngine.UI;
namespace Bindables.Samples
{
public class Example_BindToURI : MonoBehaviour
{
[Header("UI Components")]
[SerializeField]
private Image _image;
[SerializeField]
private RawImage _rawImage;
[SerializeField]
private MeshRenderer _meshRenderer;
[SerializeField]
private AudioSource _audioSource;
[Header("Bindable Data")]
[SerializeField]
private Bindable<string> _imageUri;
[SerializeField]
private Bindable<string> _audioUri;
void Start()
{
_image.BindSpriteUri(_imageUri);
_rawImage.BindTextureUri(_imageUri);
_meshRenderer.material.BindMainTextureUri(_imageUri);
_audioSource.BindClipUri(_audioUri, onLoad: () => _audioSource.Play());
}
}
}
#endif
Some important notes:
- Under the hood, this uses
UnityWebRequest. See the UnityWebRequest documentation for limitations. - Loaded files are cached. If you pass the same URI string to two different components, they will get the same asset.
- The cache works by reference counting. When all
BindContextusing the resource are unbound, the resource is destroyed.
public Bindable<string> ImageUri = new("https://somewhere.com/image.png");
void Start()
{
rawImage1.BindTextureUri(ImageUri); // one reference count
rawImage2.BindTextureUri(ImageUri); // two reference count, uses the same Texture2D
}
void Release()
{
ImageUri.Value = null;
// Both image1 and image2 become blank. Resource is released.
}
In the above exmaple, since we're using the default BindContext for rawImage1 and rawImage2, the texture will be automatically released when those two components are destroyed. You typically do not need to release it manually.