spi*_*der 4 c# unity-game-engine
我目前正在使用 Unity 的代码进行教程学习,在本节中存在额外的挑战,但不会帮助您解决它。它说我必须防止玩家向生成狗发送垃圾邮件空格键。我是 C# 新手,我开始在网上查找,但我看到了一些关于 CoRoutines 的内容,但我仍然不知道那是什么,有没有一种简单的方法可以做到这一点,在网上搜索我发现了类似的东西,但我无法使其工作。我也尝试制作一些像 canSpawn 这样的条件,但我不知道如何很好地实现它,Unity 给了我一个错误,我不能在 bool 和按键事件之间使用 &&
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerX : MonoBehaviour
{
public GameObject dogPrefab;
public float time = 2.0f;
public float timer = Time.time;
// Update is called once per frame
void Update()
{
timer -= Time.deltaTime;
if (timer > time)
{
// On spacebar press, send dog
if (Input.GetKeyDown(KeyCode.Space))
{
spawnDog();
}
timer = time;
}
void spawnDog()
{
Instantiate(dogPrefab, transform.position, dogPrefab.transform.rotation);
}
}
Run Code Online (Sandbox Code Playgroud)
你很接近。可能更容易理解逻辑的一件事是只加数而不是尝试倒数。因此,在您的情况下,代码将如下所示:
void Update ( )
{
timer += Time.deltaTime;
if ( timer >= time )
{
if ( Input.GetKeyDown ( KeyCode.Space ) )
{
spawnDog ( );
timer = 0;
}
}
}
void spawnDog ( )
{
Instantiate ( dogPrefab, transform.position, dogPrefab.transform.rotation );
}
Run Code Online (Sandbox Code Playgroud)
不断timer添加,当它大于您的time值(在本例中为 2.0f)时,它允许您按一个键。如果随后按下某个键,则timer重置为 0,并且玩家需要等待time时间 (2.0f) 才能再次按下空格键。