尝试通过FindObjectByType获取集合时无法找到对象集合

时间:2019-07-10 12:28:40

标签: 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循环的上方创建的?

1 个答案:

答案 0 :(得分:3)

FindObjectsOfType<MonoBehaviour>()在场景中找到MonoBehaviour或更好的Unity.Object。在manual中有更多信息。

  

它将不返回任何资产(网格,纹理,预制件...)或无效   对象。将不会返回已设置HideFlags.DontSave的对象。采用   Resources.FindObjectsOfTypeAll可以避免这些限制。

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");
  }