> For the complete documentation index, see [llms.txt](https://andres-organization-12.gitbook.io/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://andres-organization-12.gitbook.io/home/unity-assets/textureloader/documentation.md).

# Documentation

### Import

Use Unity's Package Manager to download and import the asset into your project. Once imported, the asset will be inside ***Assets/ARB/TextureLoader***.

### Setup

Setup TextureLoader by opening the **Settings Panel** from the "***Window > TextureLoader***" menu and selecting "***Settings***".

<figure><img src="/files/EWgUvYirDVau20nMfVDg" alt=""><figcaption><p>TextureLoader's Settings Panel</p></figcaption></figure>

### Namespace

Import TextureLoader's namespace in all scripts you want to use it:

```csharp
using ARB.TextureLoader;
```

### Usage

{% hint style="info" %}
The URL for local textures must start with **`file://`**&#x20;
{% endhint %}

{% hint style="danger" %}
Always call **`Dispose()`** or **`DisposeAll()`** methods when textures are no longer needed to avoid memory leaks.
{% endhint %}

#### Sample - Basic

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class Example : MonoBehaviour
{
    private TextureLoader loader;
    
    private readonly string url = "http://example.com/texture.jpg";
    //private readonly string url = "file://" + Path.Combine(Application.streamingAssetsPath, "texture.jpg");
    
    private void Start()
    {
        loader = TextureLoader.Load(url).OnComplete((texture) => Debug.Log("Texture loaded"));
        loader.Start();
    }

    private void OnDestroy()
    {
        loader.Dispose();
    }
}
```

#### Sample - Target

Use the **`Into()`** method to load the texture into one of the supported targets:

* UnityEngine.Renderer
* UnityEngine.SpriteRenderer
* UnityEngine.UI.Image
* UnityEngine.UI.RawImage
* UnityEngine.UIElements.VisualElement
* UnityEngine.UIElements.Image

Check the [Customize](#customize) section to override or create a new target.

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class Example : MonoBehaviour
{
    public Renderer Target;

    private TextureLoader loader;
    private readonly string url = "http://example.com/texture.jpg";

    private void Start()
    {
        loader = TextureLoader.Load(url).Into(Target);
        loader.Start();
    }

    private void OnDestroy()
    {
        loader.Dispose();
    }
}
```

#### Sample - UIToolkit

```csharp
using ARB.TextureLoader;
using UnityEngine;
using UnityEngine.UIElements;

[RequireComponent(typeof(UIDocument))]
public class Example : MonoBehaviour
{
    public VisualTreeAsset ImageTemplate;

    private TextureLoader loader;
    private readonly string url = "http://example.com/texture.jpg";

    private void Start()
    {
        VisualElement root = GetComponent<UIDocument>().rootVisualElement;
        TemplateContainer imageElement = ImageTemplate.CloneTree();
        VisualElement imageContainer = imageElement.Q("container");

        loader = TextureLoader.Load(url).Into(imageContainer);
        root.Add(imageElement);
        loader.Start();
    }

    private void OnDestroy()
    {
        loader.Dispose();
    }
}
```

#### Sample - Advanced

```csharp
using System;
using ARB.TextureLoader;
using UnityEngine;
using UnityEngine.UI;

public class Example : MonoBehaviour
{
    public RawImage Target1;
    public SpriteRenderer Target2;
    
    public Texture2D DefaultPlaceholder;
    public Texture2D LoadingPlaceholder;
    public Texture2D ErrorPlaceholder;

    private TextureLoader loader;
    private readonly string url = "http://example.com/texture.jpg";

    private void Start()
    {
        TextureSettings settings = new()
        {
            MinSize = 0,
            MaxSize = 512,
            MipmapChain = false,
            Readable = false,
            WrapMode = TextureWrapMode.Clamp,
            FilterMode = FilterMode.Bilinear,
            AnisoLevel = 0,
            Compression = TextureCompression.NormalQuality
        };

        loader = TextureLoader.Load(url, settings)
            .Into(Target1, DefaultPlaceholder, LoadingPlaceholder, ErrorPlaceholder, UGUITextureTarget.ScaleMode.ScaleToCover, fadeTime: 0.3f)
            .Into(Target2, DefaultPlaceholder, LoadingPlaceholder, ErrorPlaceholder, fadeTime: 0f)
            .OnStart(() => Debug.Log("Loading started"))
            .OnProgress(progress => Debug.Log($"Loading progress: {progress * 100}%"))
            .OnComplete((texture) => Debug.Log("Loading complete"))
            .OnError(error => Debug.LogError($"Loading error: {error}"))
            .UseCache(true, FileFormat.JPG, quality: 80, duration: TimeSpan.FromDays(7));

        loader.Start(enqueue: true);
    }

    private void OnDestroy()
    {
        loader.Dispose();
    }
}
```

#### Sample - No references

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class Example : MonoBehaviour
{
    private TextureLoader loader;
    private readonly string url1 = "http://example.com/texture1.jpg";
    private readonly string url2 = "file://" + Path.Combine(Application.streamingAssetsPath, "texture.jpg");

    private void OnEnable()
    {
        TextureLoader.OnLoadComplete += OnTextureLoadComplete;
    }

    private void Start()
    {
        TextureLoader.Load(url1);
        TextureLoader.Load(url2);
        TextureLoader.StartAll();
    }

    private void OnDisable()
    {
        TextureLoader.OnLoadComplete -= OnTextureLoadComplete;
    }

    private void OnDestroy()
    {
        TextureLoader.DisposeAll();
    }

    private void OnTextureLoadComplete(TextureLoader loader, Texture2D texture)
    {
        Debug.Log($"Texture loaded: {loader.Url}");
    }
}
```

### Codeless

Don't want or don't need to write code? Use the included components to load textures without writing any code!

Check the [Customize](#customize) section to override or create a new codeless component.

{% hint style="info" %}
By default textures are loaded on Awake and always disposed on OnDestroy.
{% endhint %}

<div><figure><img src="/files/QaYeM6gsfFAuMLDo65CM" alt=""><figcaption><p>Renderer Component</p></figcaption></figure> <figure><img src="/files/sJLYIufegIYb70JXmxss" alt=""><figcaption><p>UGUI Image Component</p></figcaption></figure> <figure><img src="/files/HNLq2ENqc907NluCxnQS" alt=""><figcaption><p>UGUI RawImage Component</p></figcaption></figure> <figure><img src="/files/Uer5lIratYhMOqckdc8M" alt=""><figcaption><p>SpriteRenderer Component</p></figcaption></figure></div>

### Customize

TextureLoader allows extending and customizing parts of its main functionality without having to modify the source code.

#### Targets

Targets are Unity components capable of rendering textures. TextureLoader can apply loaded textures to these targets through the **`Into(TextureTarget target)`** method.&#x20;

Override the included targets or create your own by inheriting from the **TextureTarget** class or any of its subclasses:

{% hint style="info" %}
Included targets: ***ARB/TextureLoader/Scripts/Targets***
{% endhint %}

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class MyTextureTarget : TextureTarget
{
    // Implement the way to get and set the texture on your target.
    protected override Texture CurrentTexture { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }

    // Use a constructor to pass the renderer you want to use as a texture target.
    public MyTextureTarget(Renderer target, float fadeTime = 0f)
        : base(fadeTime)
    {
        // Your implementation.
    }

    public override void Dispose()
    {
        // Make sure to destroy any resources that are no longer needed here.
    }

    public override void SetAlpha(float alpha)
    {
        // Implement the way to change the transparency of your renderer (if applicable).
    }

    // Fader:
    // Optional game object placed in front of the target renderer, used to create 
    // a crossfade effect between the current texture and the loaded texture.
    // Temporarily holds the current texture and fades out revealing the new texture behind.

    protected override void SetFaderAlpha(float value)
    {
        // Implement the way to change the transparency of your fader (if applicable).
    }

    protected override void SetFaderTexture(Texture texture)
    {
        // Implement the way to set the texture of the fader (if applicable).
    }
}
```

Your target is now ready to use:

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class Example : MonoBehaviour
{
    public MyTextureTarget Target;

    private TextureLoader loader;
    private readonly string url = "http://example.com/texture.jpg";

    private void Start()
    {
        loader = TextureLoader.Load(url).Into(Target);
        loader.Start();
    }

    private void OnDestroy()
    {
        loader.Dispose();
    }
}
```

#### Placeholders

Placeholders are game objects that can be optionally displayed during a loading operation when the texture is set to load into a target.

Override the included placeholders or create your own by inheriting from the **Placeholder** class or any of its subclasses:

{% hint style="info" %}
Included placeholders: ***ARB/TextureLoader/Scripts/Targets/Placeholders***
{% endhint %}

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class MyPlaceholder : Placeholder
{
    // Implement the way to know if your game object is active.
    public override bool IsActive => throw new System.NotImplementedException();

    // Use a constructor to pass the game object you want to use as a placeholder.
    public MyPlaceholder(GameObject go)
    {
        // Your implementation.
    }

    public override void Dispose()
    {
        // Make sure to destroy any resources that are no longer needed here.
    }

    public override void SetActive(bool value)
    {
        // Implement the way to enable/disable your game object here.
    }

    public override void SetAlpha(float value)
    {
        // Implement the way to change the transparency of your game object (if applicable).
    }
}
```

In order to use your new placeholder either override one of the included texture targets or create a new one. Here's an example overriding an existing texture target:

```csharp
using ARB.TextureLoader;
using UnityEngine;

public class MyRendererTextureTarget : RendererTextureTarget
{
    public MyRendererTextureTarget(Renderer target, GameObject defaultPlaceholder, GameObject loadingPlaceholder, GameObject errorPlaceholder)
        : base(target, 0f)
    {
        if (defaultPlaceholder != null)
        {
            this.defaultPlaceholder = new MyPlaceholder(defaultPlaceholder);
        }

        if (loadingPlaceholder != null)
        {
            this.loadingPlaceholder = new MyPlaceholder(loadingPlaceholder);
        }

        if (errorPlaceholder != null)
        {
            this.errorPlaceholder = new MyPlaceholder(errorPlaceholder);
        }
    }
}
```

Optionally implement an extension method:

```csharp
using ARB.TextureLoader;
using UnityEngine;

public static class TextureLoaderExtensions
{
    public static TextureLoader Into(this TextureLoader loader, Renderer target, GameObject defaultPlaceholder, GameObject loadingPlaceholder, GameObject errorPlaceholder)
    {
        return loader.Into(new MyRendererTextureTarget(target, defaultPlaceholder, loadingPlaceholder, errorPlaceholder));
    }
}
```

<pre class="language-csharp"><code class="lang-csharp">using ARB.TextureLoader;
using UnityEngine;

<strong>public class Example : MonoBehaviour
</strong>{
    public Renderer Target;
    public GameObject DefaultPlaceholder;
    public GameObject LoadingPlaceholder;
    public GameObject ErrorPlaceholder;

    private TextureLoader loader;
    private readonly string url = "http://example.com/texture.jpg";

    private void Start()
    {
        // With extension method:
        loader = TextureLoader.Load(url).Into(Target, DefaultPlaceholder, LoadingPlaceholder, ErrorPlaceholder);
        
        // Without extension method:
        //loader = TextureLoader.Load(url).Into(new MyRendererTextureTarget(target, defaultPlaceholder, loadingPlaceholder, errorPlaceholder));
        
        loader.Start();
    }

    private void OnDestroy()
    {
        loader.Dispose();
    }
}
</code></pre>

#### Codeless components

[Codeless](#codeless) components are those that can be attached to game objects with a texture renderer to load a texture without writing any code.

Override the included loader components or create your own by inheriting from the **TargetTextureLoader** class or any of its subclasses:

{% hint style="info" %}
Included components: ***ARB/TextureLoader/Scripts/Components***
{% endhint %}

```csharp
using ARB.TextureLoader;
using UnityEngine;

[AddComponentMenu("TextureLoader/My Renderer Texture Loader")]
[RequireComponent(typeof(Renderer))]
public class MyRendererTextureLoader : TargetTextureLoader
{
    private Renderer target;

    protected override TextureTarget Target => new RendererTextureTarget(target, defaultTexture, loadingTexture, errorTexture, fadeTime);

    protected override void OnValidate()
    {
        base.OnValidate();
        if (target == null) target = GetComponent<Renderer>();
    }
}
```
