所以,我有一个对象。当我按下旋转按钮时,我希望它旋转。当我按下停止按钮时,我希望它停止。
当它在void Update中时旋转很好,但是当它在它自己的函数中时,它只执行一次。我尝试使用循环但仍然没有运气。有人可以帮帮我吗?
代码C#:
public IActionResult Error()
{
// Get the details of the exception that occurred
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionFeature != null)
{
// Get which route the exception occurred at
string routeWhereExceptionOccurred = exceptionFeature.Path;
// Get the exception that occurred
Exception exceptionThatOccurred = exceptionFeature.Error;
// TODO: Do something with the exception
// Log it with Serilog?
// Send an e-mail, text, fax, or carrier pidgeon? Maybe all of the above?
// Whatever you do, be careful to catch any exceptions, otherwise you'll end up with a blank page and throwing a 500
}
return View();
}
提前致谢!
答案 0 :(得分:4)
for循环没有按预期工作,因为你没有等待一个帧。基本上,它将在一帧中进行所有旋转,并且在最终旋转之前您不会看到变化。等待框架可以使用yield return null;
来完成并且需要协程功能。
使用协程更好。您可以将boolean变量与coroutine一起使用,也可以使用StartCoroutine
和StopCoroutine
。单击开始按钮时启动旋转对象的coorutine,然后在单击停止按钮时停止协程。
public float speed = 500f;
public Button starter;
public Button stopper;
bool isSpinning = false;
IEnumerator spinnerCoroutine;
void Start()
{
//The spin function
spinnerCoroutine = spinCOR();
Button btn = starter.GetComponent<Button>();
Button butn = stopper.GetComponent<Button>();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
IEnumerator spinCOR()
{
//Spin forever untill FidgetSpinnerStop is called
while (true)
{
transform.Rotate(Vector3.up, speed * Time.deltaTime);
//Wait for the next frame
yield return null;
}
}
void FidgetSpinnerStart()
{
//Spin only if it is not spinning
if (!isSpinning)
{
isSpinning = true;
StartCoroutine(spinnerCoroutine);
}
}
void FidgetSpinnerStop()
{
//Stop Spinning only if it is already spinning
if (isSpinning)
{
StopCoroutine(spinnerCoroutine);
isSpinning = false;
}
}
答案 1 :(得分:4)
以下是一个简单的类,它使用两个按钮开始和停止旋转对象,我希望它能成为你想要实现的目标的起点。
public class TestSpin : MonoBehaviour
{
public float speed = 500f;
public Button starter;
public Button stopper;
bool IsRotating = false;
void Start()
{
Button btn = starter.GetComponent<Button>();
Button butn = stopper.GetComponent<Button>();
butn.onClick.AddListener(FidgetSpinnerStop);
btn.onClick.AddListener(FidgetSpinnerStart);
}
void FidgetSpinnerStart()
{
IsRotating = true;
}
void FidgetSpinnerStop()
{
IsRotating = false;
}
void Update()
{
if (IsRotating)
transform.Rotate(0, speed, 0);
}
}