我有一個 GameObjects 串列,其名稱如下
cube 1
cube 2
cube 3
現在我有另一個 GameObjects 串列,它們的名稱也像
sphere 4
sphere 2
sphere 8
現在我正在比較這兩個串列,如果數字匹配,我希望宣告為真。也就是說,如果立方體“2”==球體“2”,我該怎么做?兩個串列的計數也保持相等。
public List<GameObject> cube = new List<GameObject>();
public List<GameObject> sphere = new List<GameObject>();
void Start(){
for(int i=0; i<cube.Count; i ){
//Check if the string in their names for numbers match
}
}
uj5u.com熱心網友回復:
void Start(){
// step 1: store indices of cubes in dictionary
Dictionary<int, int> cubeIdToIndex = new Dictionary<int, int>();
for (int cubeIndex = 0; cubeIndex < cube.Count; cubeIndex ) {
string name = cube[cubeIndex].name;
int id = int.Parse(name.Substring(name.LastIndexOf(' ')));
cubeIdToIndex[id] = cubeIndex;
}
// step 2: check spheres
for (int sphereIndex = 0; sphereIndex < sphere.Count; sphereIndex ) {
string name = sphere[sphereIndex].name;
int id = int.Parse(name.Substring(name.LastIndexOf(' ')));
if(cubeIdToIndex.TryGetValue(id, out int cubeIndex)) {
// here cube[cubeIndex] matches sphere[sphereIndex]
}
}
}
有更有效的方法可以做到這一點,但恕我直言,這是性能和可理解性之間的良好折衷。
但是,您應該考慮重新組織您的資料結構,因為基于命名約定的匹配效率低且容易出錯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488290.html
上一篇:發生OnTriggerEnterOnTriggerExit事件時,如何為每個對撞機創建TextArea屬性欄位?