【问题标题】:Dynamically render GameObject in Unity C#在 Unity C# 中动态渲染游戏对象
【发布时间】:2019-01-02 01:11:03
【问题描述】:
我正在开发一个 AR 项目,其中虚拟对象将根据文本文件中的信息显示/隐藏在场景中。文本文件将从外部服务更新。所以我需要经常读取文件并更新场景。结果,我只有 Camera 对象,并且我在 OnPreCull() 方法中渲染场景。
文本文件包含许多对象,但并非所有对象在任何时候都在场景中。我一直在寻找一种方法来仅渲染场景中的那些对象。
在OnPreCull() 方法中创建和放置游戏对象会导致任何性能问题吗?
【问题讨论】:
标签:
c#
unity3d
augmented-reality
gameobject
culling
【解决方案1】:
在 OnPreCull() 方法中创建和放置游戏对象会产生任何性能问题吗?
是的,绝对...如果您在Update 或任何其他重复调用的方法中执行此操作也会如此。
相反,您应该在 Awake 中实例化对象,并且只激活或停用它们。
假设你有 3 个对象 A、B 和 C,我会创建一个看起来像这样的控制器类
public class ObjectsController : MonoBehaviour
{
// Define in which intervals the file should be read/ the scene should be updated
public float updateInterval;
// Prefabs or simply objects that are already in the Scene
public GameObject A;
public GameObject B;
public GameObject C;
/* Etc ... */
// Here you map the names from your textile to according object in the scene
private Dictionary<string, GameObject> gameObjects = new Dictionary<string, gameObjects>();
private void Awake ()
{
// if you use Prefabs than instantiate your objects here; otherwise you can skip this step
var a = Instantiate(A);
/* Etc... */
// Fill the dictionary
gameObjects.Add(nameOfAInFile, a);
// OR if you use already instantiated references instead
gameObjects.Add(nameOfAInFile, A);
}
}
private void Start()
{
// Start the file reader
StartCoroutine (ReadFileRepeatedly());
}
// Read file in intervals
private IEnumerator ReadFileRepeatedly ()
{
while(true)
{
//ToDo Here read the file
//Maybe even asynchronous?
// while(!xy.done) yield return null;
// Now it depends how your textile works but you can run through
// the dictionary and decide for each object if you want to show or hide it
foreach(var kvp in gameObjects)
{
bool active = someConditionDependingOnTheFile;
kvp.value.SetActive(active);
// And e.g. position it only if active
if (active)
{
kvp.value.transform.position = positionFromFile;
}
}
// Wait for updateInterval and repeat
yield return new WaitForSeconds (updateInterval);
}
}
如果您有同一个预制件的多个实例,您还应该查看Object Pooling
【解决方案2】:
我建议将每个游戏对象添加到注册表中,并通过注册表类的 Update() 循环打开或关闭它们(禁用/启用 SetActive)。
一个 Update() 进程用于检索和处理服务器文件,另一个 Update() 进程用于禁用/启用对象。听起来可能过于简单,但这是我认为获得结果的最快方法。
祝你好运!