您的位置:首页 > 移动开发 > Unity3D

Unity3D 优化 1 ( cs 实例化与内存变化)

2016-12-28 14:55 148 查看
1. 通过 public Object prefab 来实例化

测试

using UnityEngine;
using System.Collections;
using CodeStage.AdvancedFPSCounter;
public class Test : MonoBehaviour {

public Object prefab;
private GameObject go;
// Use this for initialization
void Start () {
go = GameObject.Instantiate(prefab) as GameObject;
}

void OnGUI()
{
if (GUILayout.Button("xxxxxxxxx"))
{

GameObject.Destroy(go);
go = null;
Resources.UnloadUnusedAssets();
System.GC.Collect();

}
}

void OnDestroy()
{
Resources.UnloadUnusedAssets();
System.GC.Collect();
}
}


结论:

当删除点击按钮,删除go的时候,内存没有任何变化。

当删除点击按钮,删除go的时候,接着删除挂上Test.cs的go的时候,内存有变化。

当删除点击按钮,删除go的时候,同时把prefab = null,内存有变化。

理解:

因为当删除点击按钮,删除go的时候,Test.cs 还在引用prefab,所以,prefab并不是unused,

但是,当删除点击按钮,删除go的时候,接着删除挂上Test.cs的go的时候,prefab就没有任何引用了,所以,Resources.UnloadUnusedAssets();,就直接unload了prefab。内存就是变化了。

2. 直接实例化

using UnityEngine;
using System.Collections;
using CodeStage.AdvancedFPSCounter;
public class Test : MonoBehaviour {
private GameObject go;
// Use this for initialization
void Start () {

//string path = "xxxxx.prefab";
//Object prefab = UnityEditor.AssetDatabase.LoadAssetAtPath<Object>(path);
//go = GameObject.Instantiate(prefab) as GameObject;

string path = "xxxxx";
Object prefab = Resources.Load<Object>(path);
go = GameObject.Instantiate(prefab) as GameObject;

}

void OnGUI()
{
if (GUILayout.Button("xxxxxxxxx"))
{

GameObject.Destroy(go);
go = null;
Resources.UnloadUnusedAssets();
System.GC.Collect();

}
}

}


结论

1. 用Resources.Load ,当删除点击按钮,删除go的时候,内存有变化。

2. 用UnityEditor.AssetDatabase.LoadAssetAtPath ,当删除点击按钮,删除go的时候,内存没有任何变化。

理解:

因为prefab是局部变量,那么,当删除go的时候,就prefab就没有任何的引用,那么Resources.UnloadUnusedAssets();,就直接unload了prefab。

UnityEditor.AssetDatabase.LoadAssetAtPath 可能在AssetDatabase内部,就引用了prefab,所以,Resources.UnloadUnusedAssets();就不能unload prefab


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  优化