无法从 'System.Collections.Generic.List<Object>' 转换为 'UnityEngine.Object'

Cannot convert from 'System.Collections.Generic.List<Object>' to 'UnityEngine.Object'

我对 Unity 和 C# 很陌生,我正在尝试将 json 文件解析为 Unity 中的实验对象,但我不断从 Debug.Log 行收到此错误消息说那;

Argument 2: cannot convert from 'System.Collections.Generic.List<Experiment>' to 'UnityEngine.Object'

这是我的加载 json 代码,使用 JSON .NET for Unity 资产。我的 json 文件结构为对象数组。

public void LoadJson()
  {
    using (StreamReader r = new StreamReader("exMercury.json"))
    {
      string json = r.ReadToEnd();
      List<Experiment> items = JsonConvert.DeserializeObject<List<Experiment>>(json);
      Debug.Log("Experimenter ", items);
    }
  }

json 文件:

{
  "experiments": [
    {
      "Title": "A title",
      "Ingredients": "list of ingredients",
      "Description": "description",
      "Points": 100,
      "Completed": false,
      "Steps": [
        "step 1",
        "step 2",
        "step 3",
      ],
      "Hypothesis": "",
      "Explanation": "",
      "Progress": 0.0
    },
]
}

实验结构;

using System.Collections;
using System.Collections.Generic;
using Firebase.Firestore;

[FirestoreData]
public struct Experiment
{
  [FirestoreProperty]
  public string Title { get; set; }

  [FirestoreProperty]
  public string Description { get; set; }

  [FirestoreProperty]
  public List<string> Ingredients { get; set; }

  [FirestoreProperty]
  public List<string> Steps { get; set; }

  [FirestoreProperty]
  public int Points { get; set; }

  [FirestoreProperty]
  public bool Completed { get; set; }

  [FirestoreProperty]
  public string Hypothesis { get; set; }

  [FirestoreProperty]
  public string Explanation { get; set; }

  [FirestoreProperty]
  public float Progress { get; set; }
}

任何帮助将不胜感激:)

Debug.Log作为参数

public static void Log(object message, Object context);

其中 Object 指的是 UnityEngnie.Object 并且错误告诉您 List<Experiment> 不是 UnityEngine.Object

提到的 UnityEngine.Object context 参数的实际用途如下:

如果这是例如在 MonoBehaviour 中调用,您可以添加

Debug.Log(someMessage, this);

使用组件本身作为上下文意味着当您在 Unity 中单击一次记录的消息时,相应的对象将在层次结构或资产(对于 ScriptableObjects 等)中突出显示。这样你就可以传入任何继承自 UnityEngine.Object (GameObject, Component, ScriptableObject, Texture2D, Material, ....)并使其可 ping 通。


现在我当然只能猜测,但我认为你真正想要实现的是

  • 为您的 Experiment class 实施 ToString,以便它打印出所需的信息

  • 然后使用例如

    // convert all items into their according string representation
    // see https://docs.microsoft.com/dotnet/api/system.linq.enumerable.select
    var strings = items.Select(i => i.ToString()).ToArray();
    // combine all individual string into a single one using whatever separator character you want
    // see https://docs.microsoft.com/dotnet/api/system.string.join
    var debugString = string.Join("\n\n", strings);
    // finally log this
    Debug.Log("Experiments: \n\n" + debugString);
    

或者如果你只是想检查它是否有效,你可以简单地做

Debug.Log($"Successfully loaded {items.Count} Experiments!");