[英]How I could loop over an array of objects and add a property from each object to a variable using Linq?
[英]How can I loop over objects each object after a specific time?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
public class CompareObjects : MonoBehaviour
{
public float waitTime;
private GameObject[] allObjects;
public void Compare()
{
allObjects = FindObjectsOfType<GameObject>();
foreach (GameObject go in allObjects)
{
Debug.Log(go.name + " >>>>> " + go.scene.name + " >>>>> is active object");
StartCoroutine(Comparing());
}
}
IEnumerator Comparing()
{
yield return new WaitForSeconds(waitTime);
}
}
這個想法不是阻塞整個編輯器並等待foreach
循環完成,而是讓它在第一個項目上循環等待一秒鍾,然后繼續到下一個,依此類推。
現在它讓編輯器窒息,凍結它直到循環結束。
我到目前為止所做的事情還沒有很好地工作:
我為檢查器中的按鈕創建了一個新的編輯器腳本:
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(CompareObjects))]
public class CompareObjectsButton : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
CompareObjects myTarget = (CompareObjects)target;
if (GUILayout.Button("Compare Objects"))
{
myTarget.StartComparing();
}
}
}
然后在比較對象中:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
public class CompareObjects : MonoBehaviour
{
public float waitTime;
private Coroutine comparer;
private GameObject[] allObjects;
public void StartComparing()
{
if (comparer == null)
{
comparer = StartCoroutine(Compare());
}
}
public void StopComparing()
{
if (comparer != null)
{
StopCoroutine(comparer);
comparer = null;
}
}
IEnumerator Compare()
{
while (true)
{
allObjects = FindObjectsOfType<GameObject>();
foreach (GameObject go in allObjects)
{
Debug.Log(go.name + " >>>>> " + go.scene.name + " >>>>> is active object");
yield return new WaitForSeconds(waitTime);
}
}
}
}
但它只做一個 object 而不是所有的對象。
StartCoroutine 的行為方式與啟動新線程的方式相同,因此當您調用Compare
時,您所做的只是循環遍歷游戲對象並創建事件對象,這些對象在主線程中運行時,不會阻止創建的方法它停止運行,所以最終只有新事件 object 等待指定的時間,而 main 方法繼續循環通過游戲對象的 rest 並創建更多事件對象,它本身沒有調用任何睡眠函數,而是你應該做像這樣的東西:
public void StartComparing()
{
if (comparer == null)
{
comparer = StartCoroutine(Compare());
}
}
public void StopComparing()
{
if (comparer != null)
{
StopCoroutine(comparer);
comparer = null;
}
}
IEnumerator Compare()
{
while (true)
{
allObjects = FindObjectsOfType<GameObject>();
foreach (GameObject go in allObjects)
{
Debug.Log(go.name + " >>>>> " + go.scene.name + " >>>>> is active object");
yield return new WaitForSeconds(waitTime);
}
}
}
private Coroutine comparer;
private GameObject[] allObjects;
public float waitTime;
StartComparing
將啟動一個Compare
協程,它將 go 遍歷所有對象,因此,首先 object 然后等待指定的waitTime
然后第二個StopComparing
被調用,以此類推。Compar 完成
測試了代碼,這是它的一個小(字面意思)預覽,您會看到在更改速度后它記錄對象的速度變慢:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.