Skip to main content
 首页 » 编程设计

c#之尝试通过 FindObjectOfType 获取集合时找不到对象集合

2024年02月25日38zdz8207

我正在尝试按 Tiledata 类型查找所有对象。

  using System.Collections; 
  using System.Collections.Generic; 
  using UnityEngine; 
  using UnityEngine.Tilemaps; 
  using UnityEngine.UI; 
  using System.Linq;  
 
  .... 
 
  Tiledata Test1 = new Tiledata(3, 1); 
  Debug.Log(Test1.growTime); 
  foreach(Tiledata Tile in FindObjectsOfType<MonoBehaviour>().OfType<Tiledata>()) { 
      Debug.Log("Test"); 
  }  

类:

public class Tiledata 
 { 
     public int growTime; 
     public int growLevel; 
 
     public Tiledata(int growTime1, int growLevel1) { 
        growTime = growTime1; 
        growLevel = growLevel1; 
     } 
 
 }  

我的代码没有错误。

如果我调试 Test1.growTime,我肯定得到 3。因此可以引用 Test1。

但我的问题是当我有很多 Tiledata 时,我想遍历它们。在我的 foreach 中,我尝试遍历它们,但什么也没有出现。

foreach 循环中没有执行任何代码,因此似乎没有 Tiledata 类型的对象,即使我可以引用它,并且它是在 foreach 循环之上创建的?

请您参考如下方法:

FindObjectsOfType<MonoBehaviour>()找到 MonoBehaviour ,或者更好的是 Unity.Object在现场。更多信息在 manual .

It will return no assets (meshes, textures, prefabs, ...) or inactive objects. Will not return objects that have HideFlags.DontSave set. Use Resources.FindObjectsOfTypeAll to avoid these limitations.

Tiledata不源自 MonoBehaviour , 所以它不会被发现。

要找到它(用 FindObjectsOfType )你需要从 MonoBehaviour 派生它.

public class Tiledata : MonoBehaviour 
 { 
     public int growTime; 
     public int growLevel; 
 
     public Tiledata(int growTime1, int growLevel1) { 
        growTime = growTime1; 
        growLevel = growLevel1; 
     } 
 
 } 

并将其作为 Component 添加到游戏中(这还需要附加一个 GameObject)。

Tiledata Test1 = new GameObject().AddComponent<Tiledata>(); 
  Debug.Log(Test1.growTime); 
  foreach(Tiledata Tile in FindObjectsOfType<Tiledata>()) { 
      Debug.Log("Test"); 
  }