Created
February 28, 2017 21:44
-
-
Save mqp/4efd6a8bb3a7197052342213dafcdd0e to your computer and use it in GitHub Desktop.
Illustrates different ways of loading resources in Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ResourceExample : MonoBehavior | |
{ | |
private GameObject RuntimeLoadedPrefabA; | |
private GameObject RuntimeLoadedPrefabB; | |
private GameObject RuntimeLoadedPrefabC; | |
private GameObject RuntimeLoadedPrefabD; | |
private GameObject RuntimeLoadedPrefabE; | |
private GameObject RuntimeLoadedPrefabF; | |
public void Awake() | |
{ | |
SynchronousExample(); | |
StartCoroutine(AsynchronousExample()); | |
} | |
public void SynchronousExample() | |
{ | |
// straightforward, but risky. resource loading involves at least disk seeks | |
// and maybe other overhead. it's rude to do it on the UI thread. it's more | |
// expensive the bigger the resources are -- if these prefabs have multiple | |
// behaviors and children, this may take tens or even hundreds of milliseconds | |
// during which the UI thread is blocked. it seems a lot worse on Android than PC. | |
RuntimeLoadedPrefabA = Resources.Load<GameObject>("PrefabAPath"); | |
RuntimeLoadedPrefabB = Resources.Load<GameObject>("PrefabBPath"); | |
} | |
public IEnumerator AsynchronousExample() | |
{ | |
// straightforward way to load a single resource asynchronously | |
RuntimeLoadedPrefabCRequest = Resources.LoadAsync("PrefabCPath"); | |
yield return RuntimeLoadedPrefabCRequest; // will yield until resource is ready | |
RuntimeLoadedPrefabC = (GameObject)RuntimeLoadedPrefabCRequest.asset; | |
// if you want to load multiple resources asynchronously, you can do the above | |
// approach more than once and then yield on each request in order, but you | |
// might waste a few frames at the end because of how coroutines work (i.e. | |
// Unity will only call MoveNext at most once per frame.) consider using the | |
// ResourceLoader abstraction to load them all in a batch. this will be | |
// merged momentarily (see https://github.com/AltspaceVR/UnityClient/pull/1914.) | |
var loader = new ResourceLoader(); | |
yield return loader.PreloadAll("PrefabDPath", "PrefabEPath", "PrefabFPath"); | |
RuntimeLoadedPrefabD = loader.Load<GameObject>("PrefabDPath"); | |
RuntimeLoadedPrefabE = loader.Load<GameObject>("PrefabEPath"); | |
RuntimeLoadedPrefabF = loader.Load<GameObject>("PrefabFPath"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment