2017-07-02 35 views
0
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

[RequireComponent(typeof(Rigidbody2D))] 

public class Movement : MonoBehaviour 
{ 
    //storage for the object's rigidbody 
    public Rigidbody2D rb2D; 
    //the public modifier for speed so i can edit from outside 
    public float speed; 
    //reliably take movements each second in an even, reliable manner. 
    void FixedUpdate() 
    { 
     //i move left and right if i use "a" or "d or "left" or "right" 
     float moveX = Input.GetAxis("Horizontal"); 
     //I move up and down if i use "w" or "s" or "up" or "down" 
     float moveY = Input.GetAxis("Vertical"); 
     //Vector inputs the move directions into a vector2 so i can move 
     Vector2 move = new Vector2(moveX, moveY); 
     rb2D.velocity = move * speed; 
    } 
    //following two methods are for the respective spikey builds 
    public void slow() 
    { 
     print("Shit, spike's got me!"); 
     speed = .3f; 
     StartCoroutine(PauseTheSlowdown(2.1f)); 
     speed = 1; 
    } 
    public void Bigslow() 
    { 
     print("HOLY CRAP THAT HURT"); 
     speed = 0f; 
     StartCoroutine(PauseTheSlowdown(3.7f)); 
     speed = 1; 
    } 

    IEnumerator PauseTheSlowdown(float seconds) 
    { 
     print("Pause this crap"); 
     yield return new WaitForSecondsRealtime(seconds); 
    } 

} 

我在这里遇到了一些问题,我的代码似乎很完美。它运行,然后当一个外部脚本从任何一个尖峰方法中拉出时,它的行为就像协程并不在那里,并且从慢速回到全速。 除了协程以外,没有任何错误或问题根本不会导致等待发生。我在这里错过了很明显的东西吗试图让一个方法暂停使用协程,我做错了什么?

回答

1

你不能把必须暂停在正常功能的代码。你必须把它放入协程函数中。

例如,在您的Bigslow函数中,Speed变量将被设置为0。协程PauseTheSlowdown将启动。 Unity将仅在PauseTheSlowdown函数中等待一帧,然后返回到Bigslow,其中速度设置为1。它不会等待,因为您是从void函数开始的。

你有两个选择:

。使您的slowBigslow功能是IEnumerator代替void然后产生时StartCoroutine被调用。

public IEnumerator slow() 
{ 
    print("Shit, spike's got me!"); 
    speed = .3f; 
    yield return StartCoroutine(PauseTheSlowdown(2.1f)); 
    speed = 1; 
} 

public IEnumerator Bigslow() 
{ 
    print("HOLY CRAP THAT HURT"); 
    speed = 0f; 
    yield return StartCoroutine(PauseTheSlowdown(3.7f)); 
    speed = 1; 
} 

IEnumerator PauseTheSlowdown(float seconds) 
{ 
    print("Pause this crap"); 
    yield return new WaitForSecondsRealtime(seconds); 
} 

通知之yield return调用StartCoroutine之前。

.Move要执行,并等待一段时间到PauseTheSlowdown协程函数的代码:

public void slow() 
{ 
    print("Shit, spike's got me!"); 
    StartCoroutine(PauseTheSlowdown(2.1f, .3f, 1)); 
} 
public void Bigslow() 
{ 
    print("HOLY CRAP THAT HURT"); 
    StartCoroutine(PauseTheSlowdown(3.7f, 0f, 1)); 
} 

IEnumerator PauseTheSlowdown(float seconds, float before, float after) 
{ 
    print("Pause this crap"); 
    speed = before; 
    yield return new WaitForSecondsRealtime(seconds); 
    speed = after; 
} 
+0

这回答了很多问题,谢谢。我马上试一试。 –

相关问题