如何解决 IEnumerator(Unity, C#) 的错误?

我需要让我的角色墙运行,但我有代码问题IEnumerator


这是用Unity 4.5.xC# 编写的代码


using UnityEngine;

using System.Collections;


public class Moving : MonoBehaviour {


public float speed = 6.0F;

public float jumpSpeed = 8.0F; 

public float gravity = 20.0F;

public float runTime = 1.0f;

private Vector3 moveDirection = Vector3.zero;

private bool isWallL = false;

private bool isWallR = false;

private RaycastHit hitL;

private RaycastHit hitR;

private int jumpCount = 1;


IEnumerator afterRun() {

    yield return new WaitForSeconds (runTime);

    isWallL = false;

    isWallR = false;

    gravity = 20;

}

void Update() {

    CharacterController controller = GetComponent<CharacterController>();


    if (controller.isGrounded) {

        jumpCount = 0;

        moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

        moveDirection = transform.TransformDirection(moveDirection);

        moveDirection *= speed;


        if (Input.GetButton("Jump"))

            moveDirection.y = jumpSpeed;

    }


    if (Input.GetKeyDown (KeyCode.Space) && !controller.isGrounded && jumpCount <= 1) {

        if (Physics.Raycast (transform.position, -transform.right, out hitL, 1)){

            if (hitL.transform.tag == "Wall"){

                isWallL = true;

                isWallR = false;

                jumpCount = 1;

                gravity = 0;

                StartCoroutine (afterRun);

            }

        }

        if (Physics.Raycast (transform.position, transform.right, out hitR, 1)){

            if (hitR.transform.tag == "Wall"){

                isWallL = false;

                isWallR = true;

                jumpCount = 1;

                gravity = 0;

                StartCoroutine (afterRun);

            }

        }

    }

    moveDirection.y -= gravity * Time.deltaTime;

    controller.Move(moveDirection * Time.deltaTime);

    }

}

预计没有错误,但我有两个:


错误CS1502:UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)'的最佳重载方法匹配有一些无效参数”和“错误CS1503:参数#1'无法将方法组'表达式转换为类型System.Collections.IEnumerator' 。


largeQ
浏览 195回答 3
3回答

慕斯709654

代码中的 afterRun 是一个函数,但您在调用它时不使用括号。所以:StartCoroutine (afterRun());例如:namespace someNamespace{     public class SomeClass    {        IEnumerator afterRun()        {            yield return new WaitForSeconds(3);                    }        public void Test(IEnumerator enumerator)        {            while(enumerator.MoveNext())            {                //do some work            }        }        public void YoureCode()        {            Test(afterRun());        }    }    public class WaitForSeconds    {        public WaitForSeconds(int a)        {                    }    }}

jeck猫

为什么不这样:private IEnumerator coroutine;然后设置并调用它:coroutine = afterRun();StartCoroutine(coroutine);

波斯汪

根据 Unity协程的文档,看来协程函数必须被调用为StartCoroutine ("afterRun");
打开App,查看更多内容
随时随地看视频慕课网APP