寻找一种更有效的方法来找到特定类型的游戏对象



感谢您看到这篇文章!

下面的这个函数是一个较大脚本的一部分,该脚本引用了一个单独的GameObject中的脚本。虽然一切都按预期进行,但很明显,使用GameObject.Find((并不是最有效的方法,尤其是因为该函数在给定时间被调用多次,主要是作为foreach循环的一部分。

[SerializeField] private int maximumX;
[SerializeField] private int maximumY;
public void Example(int x, int y)
{
if (x < 0 || x > (maximumX - 1) || y < 0 || y > (maximumY - 1))
{
Debug.LogError("Object (" + x + ", " + y + ") does not exist");
}
else
{
SampleScript targetExample = GameObject.Find("Object (" + x + ", " + y + ")").GetComponent<SampleScript>();
//Returns three public variables from targetExample
//Note that "x" and "targetExample.xCoordinate" are the same (as well as both Y's)
//While the bool "isValid" varies between each "SampleScript" in the scene
Debug.Log(targetExample + " X value: " + targetExample.xCoordinate);
Debug.Log(targetExample + " Y value: " + targetExample.yCoordinate);
Debug.Log(targetExample + " isValid: " + targetExample.isValid);
}
}

给定场景中有几个预制件具有此SampleScript组件,每个预制件都有一个唯一的isValid布尔值,以及一个X和Y坐标(由xCordinate/yCordinate表示(。每个游戏对象具有表示其X/Y坐标系的唯一名称(例如"对象(1到目前为止,这是我定位特定物体的方法。请注意,这些数字并不一定与GameObject的世界变换相匹配。

我完全错过了一个更简单的解决方案,但任何帮助都会很棒!谢谢

如果对象在开始时存在,则迭代所有GameObjects并在Dictionary<字符串,游戏对象>按名称,这将在更新期间更有效地使用。

如果对象在开始时不存在,请创建相同的Dictionary,但不要预先填充它,而是使用ContainsKey查看您是否有引用,如果没有,则使用GameObject。Find在那时将其添加到字典中,这样您只会受到一次时间惩罚:

string key = "Object (" + x + ", " + y + ")";
if(!ObjectDict.ContainsKey(key))
{
ObjectDict.Add(key,GameObject.Find(key));
}
SampleScript targetExample = ObjectDict[key].GetComponent<SampleScript>();

(如果您销毁任何对象,请确保也将其从字典中删除(

最新更新