using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class GameObjectInfo : MonoBehaviour
{
[System.Serializable]
public class GameObjectstInfo
{
public GameObject parent;
public int childrenCount;
public List<Transform> children = new List<Transform>();
}
public string gameObjectsInfo = "";
public GameObjectstInfo[] objectsinfo;
private bool searching = false;
// Start is called before the first frame update
void Start()
{
Search();
}
private void Update()
{
}
public void Search()
{
if (gameObjectsInfo != "")
{
var foundObjects = FindGameObjectsWithName(gameObjectsInfo);
objectsinfo = new GameObjectstInfo[foundObjects.Length];
for (int i = 0; i < foundObjects.Length; i++)
{
objectsinfo[i] = new GameObjectstInfo();
objectsinfo[i].parent = foundObjects[i];
foreach (Transform child in foundObjects[i].transform)
{
objectsinfo[i].childrenCount += 1;
objectsinfo[i].children.Add(child);
}
}
}
}
GameObject[] FindGameObjectsWithName(string nameIt)
{
int it = 0;
GameObject[] objArr;
bool b = false;
while (!b)
{
if (GameObject.Find(nameIt))
{
GameObject.Find(nameIt).name = nameIt + it;
it++;
}
else
{
b = true;
}
}
objArr = new GameObject[it];
while (it > 0)
{
it--;
objArr[it] = GameObject.Find(nameIt + it);
objArr[it].name = nameIt;
}
return objArr;
}
}
仅在字符串var gameObjectsInfo不为空的情况下,我才想使Search();
一次搜索一次,并且如果用户更改var gameObjectsInfo内部的字符串,则每次都进行新搜索。但是,每次搜索一次,如果字符串已更改,则进行新搜索。
主要目标是能够在“更新”中或使用按钮进行实时搜索。按钮部分工作正常,但我希望也能在更新中实时搜索。
按钮脚本:
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(GameObjectInfo))]
public class GameObjectInfoButton : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
GameObjectInfo myScript = (GameObjectInfo)target;
if (GUILayout.Button("Search"))
{
myScript.Search();
}
}
}
答案 0 :(得分:5)
我认为一个解决方案可能是这样的:存储gameObjectsInfo
的先前状态并与当前gameObjectsInfo
进行比较。如果它们不相等,则gameObjectsInfo
已更改。
...
public string previousGameObjectsInfo = ""; // to store the previous state
public string gameObjectsInfo = "";
...
private void Update()
{
if(gameObjectsInfo != "" && gameObjectsInfo != previousGameObjectsInfo)
{
Search(); // or anything else
}
previousGameObjectsInfo = gameObjectsInfo;
}