将Coroutine函数添加到Transform

问题描述 投票:0回答:2

我正在创建一个扩展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指令或汇编引用?)”

unity3d transform extension-methods
2个回答
6
投票
  1. 你不能把Coroutine称为一种方法,你宁愿通过StartCoroutine()启动它。当你像普通方法一样调用它时,它将被忽略(正如你已经注意到的那样)。
  2. 你不能使用transform.StartCoroutine(),因为TransformComponent类型并且不继承MonoBehaviour。 但StartCoroutine()只能用于MonoBehaviour

因此,假设您已经在MonoBehaviour内调用它,因为使用了transform而只是做

StartCoroutine(transform.tester());

只要从MonoBehaviour内部或者另外调用,它对我来说完全没问题

anyGameObject.GetComponent<MonoBehaviour>().StartCoroutine(transform.tester());

将运行MonoBehaviour的其他Coroutine甚至不必在同一个对象上,但你必须确保MonoBehaviour附加任何其他anyGameObject脚本。


1
投票

你无法启动协程,如函数调用添加一个启动协同程序的函数。此外,因为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();
© www.soinside.com 2019 - 2024. All rights reserved.