unity3d————异步加载练习题
1. 代码示例:
ResourcesMgr类
public class ResourcesMgr
{
private static ResourcesMgr instance = new ResourcesMgr();
public static ResourcesMgr Instance => instance;
private ResourcesMgr()
{
}
public void LoadRes<T>(string name, UnityAction<T> callBack) where T:Object
{
ResourceRequest rq = Resources.LoadAsync<T>(name);
rq.completed += (a) =>
{
//直接得到 传入的 对象 通过它得到资源内容 然后转换成对应类型 传出去 外面不需要转换 直接使用
callBack((a as ResourceRequest).asset as T);
};
}
}
Lesson18Test 类
public class Lesson18Test : MonoBehaviour
{
private Texture tex;
// Start is called before the first frame update
void Start()
{
ResourcesMgr.Instance.LoadRes<Texture>("Tex/TestJPG", (obj) =>
{
tex = obj;
});
//ResourceRequest rq= Resources.LoadAsync<Texture>("Tex/TestJPG");
//rq.completed += (a) =>
//{
//tex = (a as ResourceRequest).asset as Texture;
//};
}
private void OnGUI()
{
if(tex != null)
GUI.DrawTexture(new Rect(0, 0, 100, 100), tex);
}
}
2.代码示例
public class SceneMgr
{
private static SceneMgr instance = new SceneMgr();
public static SceneMgr Instance => instance;
private SceneMgr() { }
public void LoadScene(string name, UnityAction action)
{
AsyncOperation ao = SceneManager.LoadSceneAsync(name);
ao.completed += (a) =>
{
//通过那么大表达式 包裹一层
//在内部 直接调用外部传入的委托即可
action();
};
}
}
public class Lesson20Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
SceneMgr.Instance.LoadScene("Lesson20Test", () => {
print("加载结束");
});
}
// Update is called once per frame
void Update()
{
}
}
原文地址:https://blog.csdn.net/2401_82978699/article/details/143816912
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!