我正在创建一个扩展Transform的统一脚本
using UnityEngine;
using System.Collections;
using UnityEditor;
public static class TransformExtension
{
//lots of functions
public static IEnumerator tester(this Transform test)
{
Debug.Log("hello");
yield return null;
}
public static void tester2(this Transform test)
{
Debug.Log("hello2");
}
}
当我调用
transform.tester();
transform.tester2();
只记录“hello2”。
当我试着
StartCoroutine(transform.tester());
我收到以下错误:
“错误CS0103:当前上下文中不存在名称'tester'”
“Transform”不包含'StartCoroutine'的定义,并且没有可访问的扩展方法'StartCoroutine'接受类型'Transform'的第一个参数(你是否缺少using指令或汇编引用?)
当我试着
transform.StartCoroutine(transform.tester());
我有:
“错误CS1061:'转换'不包含'StartCoroutine'的定义,并且没有可访问的扩展方法'StartCoroutine'接受类型'Transform'的第一个参数(你是否缺少using指令或汇编引用?)”
StartCoroutine()
启动它。当你像普通方法一样调用它时,它将被忽略(正如你已经注意到的那样)。transform.StartCoroutine()
,因为Transform
是Component
类型并且不继承MonoBehaviour
。
但StartCoroutine()
只能用于MonoBehaviour
。因此,假设您已经在MonoBehaviour
内调用它,因为使用了transform
而只是做
StartCoroutine(transform.tester());
只要从MonoBehaviour
内部或者另外调用,它对我来说完全没问题
anyGameObject.GetComponent<MonoBehaviour>().StartCoroutine(transform.tester());
将运行MonoBehaviour
的其他Coroutine甚至不必在同一个对象上,但你必须确保MonoBehaviour
附加任何其他anyGameObject
脚本。
你无法启动协程,如函数调用添加一个启动协同程序的函数。此外,因为derHugo指出你需要Monobehavior来实现这一点,你可以通过你的变换访问MonoBehavior,如下所示:
public static IEnumerator Tester()
{
Debug.Log("hello");
yield return null;
}
public static void StartTester(this Transform test)
{
test.GetComponent<MonoBehaviour>().StartCoroutine(Tester());
}
public static void tester2(this Transform test)
{
Debug.Log("hello2");
}
然后这样做:
transform.startTester();