You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the main thread somewhere at the start of the project need to call `ImageLoader.Init();` once to initialize static properties in the right thread. It is required to make in the main thread. Then you can use `ImageLoader` from any thread and at any time.
98
105
99
-
```C#
106
+
```csharp
100
107
ImageLoader.Init(); // just once from the main thread
101
108
```
102
109
@@ -106,7 +113,7 @@ ImageLoader.Init(); // just once from the main thread
106
113
107
114
`ImageLoader.LoadSprite` returns `IFuture<Sprite>`. This instance provides all range of callbacks and API to modify it. [Understanding `IFuture<T>`](#understanding-ifuturet).
108
115
109
-
```C#
116
+
```csharp
110
117
ImageLoader.LoadSprite(imageURL) // loading process started
// Clear memory Memory and Disk cache for all images
365
372
ImageLoader.ClearCacheAll();
366
373
@@ -390,7 +397,7 @@ Texture2D objects consume a lot of memory. Ignoring it may impact performance or
390
397
391
398
It is simple, just executing this line of code would release memory of a single Texture2D in the case if no other `Reference` pointing on it exists. Before doing that please make sure that no Unity component is using the texture.
392
399
393
-
```C#
400
+
```csharp
394
401
ImageLoader.ClearMemoryCache(url);
395
402
```
396
403
@@ -402,7 +409,7 @@ Under the hood it calls `UnityEngine.Object.DestroyImmediate(texture)`.
402
409
403
410
ImageLoader can manager memory releasing of loaded textures. To use it need to call `ImageLoader.LoadSpriteRef` instead of `ImageLoader.LoadSprite`. It returns `Reference<Sprite>` object which contains `Sprite` and `Url`. When `Reference<Sprite>` object is not needed anymore, call `reference.Dispose()` method to release memory, or just don't save the reference on it. It is `IDisposable` and it will be disposed by Garbage Collector. Each new instance of `Reference<Sprite>` increments reference counter of the texture. When the last reference is disposed, the texture memory releases. Also, if any reference is alive, calling `ImageLoader.ClearMemoryCache` or `ImageLoader.ClearCache` would have zero effect for only referenced textures. It prints warning messages about it.
`Reference<T>.ThenSet` has a unique feature to attach the reference to the target consumer if consumer is `UnityEngine.Component`. The reference would be disposed as only the consumer gets destroyed.
426
433
427
-
```C#
434
+
```csharp
428
435
ImageLoader.LoadSpriteRef(imageURL) // load sprite using Reference
429
436
.ThenSet(image) // if success set sprite into image, also creates binding to `image`
430
437
.Forget();
@@ -434,7 +441,7 @@ ImageLoader.LoadSpriteRef(imageURL) // load sprite using Reference
434
441
435
442
It automatically dispose the reference as only `this.gameObject` gets `OnDestroy` callback.
436
443
437
-
```C#
444
+
```csharp
438
445
ImageLoader.LoadSpriteRef(imageURL) // load sprite using Reference
@@ -447,14 +454,113 @@ ImageLoader.LoadSpriteRef(imageURL) // load sprite using Reference
447
454
448
455
#### Get references count
449
456
450
-
```C#
457
+
```csharp
451
458
varcount=ImageLoader.GetReferenceCount(imageURL); // get count of references
452
459
```
453
460
461
+
---
462
+
454
463
# Other
455
464
456
465
## Understanding `IFuture<T>`
457
466
467
+
The `IFuture<T>` interface represents an asynchronous operation that will eventually produce a result of type `T`. It provides a range of methods and properties to handle the lifecycle of the asynchronous operation, including loading, success, failure, and cancellation events.
468
+
469
+
### Key Properties of `IFuture<T>`
470
+
471
+
-**`Id`**: Unique identifier for the future.
472
+
-**`Url`**: URL associated with the future.
473
+
-**`IsCancelled`**: Indicates if the operation has been cancelled.
474
+
-**`IsLoaded`**: Indicates if the operation has successfully loaded the result.
475
+
-**`IsCompleted`**: Indicates if the operation has completed (either successfully or with an error).
476
+
-**`IsInProgress`**: Indicates if the operation is currently in progress.
477
+
-**`Status`**: Current status of the future.
478
+
-**`CancellationToken`**: Token used to cancel the operation.
479
+
-**`Value`**: The result of the operation.
480
+
-**`LogLevel`**: The logging level for the operation.
481
+
482
+
### Key Methods of `IFuture<T>`
483
+
484
+
-**``Then(Action<T> onCompleted)``**: Registers a callback to be executed when the operation successfully completes and produces a result.
485
+
-**`Failed(Action<Exception> action)`**: Registers a callback to be executed if the operation fails with an exception.
486
+
-**`Completed(Action<bool> action)`**: Registers a callback to be executed when the operation completes, regardless of success or failure. The boolean parameter indicates whether the operation was successful.
487
+
-**`Canceled(Action action)`**: Registers a callback to be executed if the operation is canceled.
488
+
-**`SetUseDiskCache(bool value = true)`**: Configures whether the operation should use disk caching.
489
+
-**`SetUseMemoryCache(bool value = true)`**: Configures whether the operation should use memory caching.
490
+
-**`SetLogLevel(DebugLevel value)`**: Sets the logging level for the operation.
491
+
-**`Cancel()`**: Cancels the operation if it is still in progress.
492
+
-**`Forget()`**: Ignores the result of the operation, useful for avoiding compilation warnings about unawaited tasks.
493
+
-**`AsUniTask()`**: Converts the `IFuture<T>` instance to a `UniTask<T>`.
494
+
-**`AsTask()`**: Converts the `IFuture<T>` instance to a `Task<T>`.
495
+
-**`AsReference(DebugLevel logLevel = DebugLevel.Trace)`**: Converts the `IFuture<T>` instance to a `Future<Reference<T>>` instance.
496
+
-**`GetAwaiter()`**: Returns an awaiter for the `IFuture<T>` instance, allowing it to be awaited using the `await` keyword.
497
+
-**`PassEvents(IFutureInternal<T> to, bool passCancelled = true)`**: Passes events to another future.
498
+
-**`PassEvents<T2>(IFutureInternal<T2> to, Func<T, T2> convert, bool passCancelled = true)`**: Passes events to another future with conversion.
499
+
-**`Register(CancellationToken cancellationToken)`**: Registers a new cancellation token to cancel the future with it.
500
+
-**`Timeout(TimeSpan duration)`**: Sets a timeout duration for the future. If the duration is reached, it fails the future with a related exception.
501
+
502
+
### Example Usage of `IFuture<T>`
503
+
504
+
```csharp
505
+
ImageLoader.LoadSprite(imageURL) // Start loading the sprite
506
+
.Then(sprite=>Debug.Log("Loaded")) // On successful load
507
+
.Failed(exception=>Debug.LogException(exception)) // On failure
508
+
.Completed(isLoaded=>Debug.Log($"Completed, isLoaded={isLoaded}")) // On completion
509
+
.Canceled(() =>Debug.Log("Canceled")) // On cancellation
510
+
.Forget(); // Avoid compilation warnings
511
+
```
512
+
458
513
## Understanding `Reference<T>`
459
514
515
+
The `Reference<T>` class is used to manage the lifecycle of loaded resources, such as `Texture2D` or `Sprite`, in a memory-efficient manner. It helps to automatically release memory when the resource is no longer needed, preventing memory leaks and optimizing performance.
516
+
517
+
### Key Properties of `Reference<T>`
518
+
519
+
-**`Value`**: The actual resource (e.g., `Sprite` or `Texture2D`) that is being referenced.
520
+
-**`Url`**: The URL associated with the resource.
521
+
-**`IsDisposed`**: Indicates whether the reference has been disposed.
522
+
523
+
### Key Methods of `Reference<T>`
524
+
525
+
-**`Dispose()`**: Disposes the reference, releasing the associated resource from memory. This should be called when the resource is no longer needed.
526
+
-**`DisposeOnDestroy(Component component)`**: Automatically disposes the reference when the specified `Component` is destroyed. This is useful for ensuring that resources are released when the associated GameObject is destroyed.
527
+
-**`DisposeOnDisable(Component component)`**: Automatically disposes the reference when the specified `Component` is disabled.
528
+
-**`DisposeOnEnable(Component component)`**: Automatically disposes the reference when the specified `Component` is enabled.
The `Future<Reference<T>>` class combines the functionality of `IFuture<T>` and `Reference<T>`, providing a powerful tool for managing the lifecycle of asynchronous operations that produce resources such as `Texture2D` or `Sprite`. This combination allows you to handle the loading process and the resource management in a memory-efficient manner.
558
+
559
+
### Why It Is Needed
560
+
561
+
The `Future<Reference<T>>` class is needed to ensure that resources are loaded asynchronously and managed efficiently. By using this class, you can:
562
+
563
+
1.**Load Resources Asynchronously**: Start loading resources such as `Texture2D` or `Sprite` without blocking the main thread.
564
+
2.**Manage Resource Lifecycle**: Automatically release resources when they are no longer needed, preventing memory leaks and optimizing performance.
565
+
3.**Handle Loading Events**: Register callbacks for various events such as success, failure, and cancellation during the loading process.
566
+
4.**Bind Resources to Components**: Automatically dispose of resources when the associated `UnityEngine.Component` is destroyed, ensuring that resources are released when the GameObject is destroyed.
0 commit comments