Rup*_*ure 3 c# optimization unity-game-engine
使用Unity,我正在开发一款游戏,所有Gameobjects带有某个标签的游戏都会定期消失/重新出现(平均每10秒钟).我GameObject.FindGameObjectsWithTag()用来创建一个Gameobject[]通过我每次枚举对象需要可见/不可见的通过.我不能在Start上调用它一次,因为Gameobjects在播放时会创建新的.我认为Gameobject[]每次创建/销毁某些内容时访问和更改都会更糟.有没有更好的方法来处理这个问题.我知道GameObject.Find方法对性能的影响有多严重......
是的,有一种更好的方法可以做到这一点.有一个带有List可以存储GameObjects的变量的脚本.使它成为单身人士更好但不是必需的.
这个单例脚本应该附加到一个空的GameObject:
public class GameObjectManager : MonoBehaviour
{
//Holds instance of GameObjectManager
public static GameObjectManager instance = null;
public List<GameObject> allObjects = new List<GameObject>();
void Awake()
{
//If this script does not exit already, use this current instance
if (instance == null)
instance = this;
//If this script already exit, DESTROY this current instance
else if (instance != this)
Destroy(gameObject);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,写自己注册到一个脚本List的GameObjectManager 脚本.它应该在Awake函数中注册自己并在函数中取消注册OnDestroy.
必须将此脚本附加到要添加到列表的每个预制件.只需从编辑那里做到:
public class GameObjectAutoAdd : MonoBehaviour
{
void Awake()
{
//Add this GameObject to List when it is created
GameObjectManager.instance.allObjects.Add(gameObject);
}
void OnDestroy()
{
//Remove this GameObject from the List when it is about to be destroyed
GameObjectManager.instance.allObjects.Remove(gameObject);
}
}
Run Code Online (Sandbox Code Playgroud)
如果GameObjects不是预制件而是通过代码创建的GameObjects,只需在创建GameObjectAutoAdd脚本后将脚本附加到它们:
GameObject obj = new GameObject("Player");
obj.AddComponent<GameObjectAutoAdd>();
Run Code Online (Sandbox Code Playgroud)
您现在可以GameObjects在列表中 访问您的索引号GameObjectManager.instance.allObjects[n];在哪里n,您不必再使用任何Find函数来查找GameObject.
| 归档时间: |
|
| 查看次数: |
776 次 |
| 最近记录: |