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);
}
}
我在这里遇到了一些问题,我的代码似乎完全正常。它运行,然后当一个外部脚本从任何一个尖峰方法中拉出时,它的行为就像协同程序甚至没有那样,并且从慢速向后移动到全速。 除了协同程序之外没有任何错误或问题,只是不会导致等待发生。我错过了一些明显的东西吗?
答案 0 :(得分:1)
您无法将必须暂停的代码放入正常功能中。你必须把它放在协程函数中。
例如,在Bigslow
函数中,Speed
变量将设置为0
。 PauseTheSlowdown
协程将启动。 Unity将仅在PauseTheSlowdown
函数中等待一帧,然后返回速度设置为Bigslow
的{{1}}。它不会等待,因为您是从1
函数启动它。
您有两种选择:
1 。将void
和slow
函数设为Bigslow
而不是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
。
2 。移动您要执行的代码并等待一段时间到StartCoroutine
协同程序函数:
PauseTheSlowdown