如何解决我无法使用 unity 的 Object.FindObjectOfType 在脚本中找到有效方法的问题?

How do I fix my failure to find a valid method in a script using unity's Object.FindObjectOfType?

我试图让 TestGrab 找到脚本 PlatformStateMachine 并执行 LoadChaptersMenu 方法,但是下面的注释行有错误:对象没有 LoadChaptersMenu 的定义,也没有接受第一个参数的扩展方法对象等等,常见错误。我不知道我是如何未能 select 或公开该方法的。

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    
    public class Test : MonoBehaviour
    {
        public void TestGrab ()
      {
            UnityEngine.Debug.Log("triggered");
            object psm = Object.FindObjectOfType<PlatformStateMachine>();
            psm.LoadChaptersMenu();// error shows up here

  }

PlatformStateMachine.cs:

using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;



public class PlatformStateMachine : MonoBehaviour
{
    public static void LoadChaptersMenu()
    {
         UnityEngine.Debug.Log("executed");
    }
}

有人可能会在其他地方找到答案,但由于我对该问题的了解有限,我无法在搜索中找到这样的解决方案。如果存在语法错误,我无法统一执行代码进行调试,除了在这里询问之外,不知道要采取什么故障排除步骤。

Test.cs

using UnityEngine;

public class Test : MonoBehaviour
{
    public void TestGrab()
    {
        Debug.Log("triggered");
        var psm = FindObjectOfType<PlatformStateMachine>();
        psm.LoadChaptersMenu();
    }
}

PlatformStateMachine.cs

using UnityEngine;

public class PlatformStateMachine : MonoBehaviour
{
    public void LoadChaptersMenu()
    {
        Debug.Log("executed");
    }
}

在 Test.cs 中,您将 PlatformStateMachine 隐式转换为一个对象,对象是所有对象的超级 class,并且没有 LoadChaptersMenu 方法。

由于在使用FindObjectOfType时获取的是PlatformStateMachine实例,不想使用静态方法,所以我去掉了PlatformStateMachine.cs中的static修饰符。 如果您希望该方法是静态的,请以静态方式调用它,例如:

PlatformStateMachine.LoadChaptersMenu();

在寻找对象之前或之后进行检查就可以了。 例如:

var psm = FindObjectOfType<PlatformStateMachine>();
if(psm == null)
   throw new System.Exception("Object of type " + typeof(PlatformStateMachine) + " not found!");
psm.LoadChaptersMenu()

但我建议做一个 public 参考,以便从内存中保存。因为 FindObjectOfType 在调用时会占用大量内存。 抱歉英语不好!!!