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

标签 c# unity3d

我正在尝试按 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");
  } 

关于c# - 尝试通过 FindObjectOfType 获取集合时找不到对象集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56970733/

相关文章:

c# - 编程 "Lean left and Lean right"- Kinect 中的手势

unityscript - 我可以在 Unity 5 中知道谁实例化了对象吗?

c# - 字符串中的文件目录

c# - 如何让媒体播放器使用 C# *播放*?

c# - Unity 广告没有自动初始化?

multithreading - Unity : How to use all CPU cores for Camera. 使用多线程图形作业渲染?优化 - 不起作用?

c# - 使用图像参数时 Unity 连接到 Dall-E API?

c# - 如何限制用户登录?

c# - GeckoFX - 实现搜索功能 - 如何使用 nsIWebBrowserFind 接口(interface)

C# - 2 个客户端程序交易变量信息——有更好的方法吗?