如何在一定时间后将变量设置为零
问题描述:
因此,我正在尝试将乒乓游戏作为Unity的学习活动。我正在努力为乒乓球制造一个复位系统,如果它被卡在永久弹跳下来的话。如何在一定时间后将变量设置为零
我设置的底壁对撞机触发和顶壁撞机触发1。例如递增一个接触变量,如果球击中了游戏的顶壁HitsTop
变量将通过1
对于底壁同样如此。我的问题是,当球击中底壁和顶壁十次时,它会重置球的位置。
我想添加一些代码,在一段时间后,比如说5秒,将重置HitsTop
和HitsBottom
变量。
这是可能的C#?
我的代码,例如:
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public static int PlayerScore1 = 0;
public static int PlayerScore2 = 0;
public static int HitsTop = 0;
public static int HitsBottom = 0;
public GUISkin layout;
Transform theBall;
// Use this for initialization
void Start() {
theBall = GameObject.FindGameObjectWithTag("Ball").transform;
}
public static void Score (string wallID) {
if (wallID == "rightWall")
{
PlayerScore1++;
} else if (wallID == "leftWall") {
PlayerScore2++;
}
if (wallID == "topWallTrigger")
{
HitsTop++;
} else if (wallID == "bottomWallTrigger") {
HitsBottom++;
}
}
void OnGUI() {
GUI.skin = layout;
GUI.Label(new Rect(Screen.width/2 - 150 - 12, 20, 100, 100), "" + PlayerScore1 + HitsTop);
GUI.Label(new Rect(Screen.width/2 + 150 + 12, 20, 100, 100), "" + PlayerScore2 + HitsBottom);
if (GUI.Button(new Rect(Screen.width/2 - 60, 35, 120, 53), "RESTART"))
{
PlayerScore1 = 0;
PlayerScore2 = 0;
HitsTop = 0;
HitsBottom = 0;
theBall.gameObject.SendMessage("RestartGame", 0.5f, SendMessageOptions.RequireReceiver);
}
if (PlayerScore1 == 10)
{
GUI.Label(new Rect(Screen.width/2 - 150, 200, 2000, 1000), "PLAYER ONE WINS");
theBall.gameObject.SendMessage("ResetBall", null, SendMessageOptions.RequireReceiver);
} else if (PlayerScore2 == 10)
{
GUI.Label(new Rect(Screen.width/2 - 150, 200, 2000, 1000), "PLAYER TWO WINS");
theBall.gameObject.SendMessage("ResetBall", null, SendMessageOptions.RequireReceiver);
}
if (HitsTop == 10) {
theBall.gameObject.SendMessage("RestartGame", 1.0f, SendMessageOptions.RequireReceiver);
HitsTop = 0;
} else if (HitsBottom == 10) {
theBall.gameObject.SendMessage("RestartGame", 1.0f, SendMessageOptions.RequireReceiver);
HitsBottom = 0;
}
}
}
答
使用Time.deltaTime
递减的变量。
float timer = 5;
void Update()
{
//This will decrement the timer's value by the time. Once this hits zero, the timer is reset to its original value.
timer -= Time.deltaTime;
if(timer <= 0)
{
//Call reset game function
timer = 5;
}
}
此外,当你增加HitsTop
或HitsBottom
,计时器重置为5
+0
这段代码对我来说非常合适。非常感谢! :) –
+1
很高兴成为服务 –
是有可能在C# - 请张贴一些代码。 –