我目前已将此代码附加到玩家身上,以启动计时器,该计时器在输入触发器时结束,但是我想使其在输入触发器而不是在开始游戏时启动。
public class Timer : MonoBehaviour
{
public Text timerText;
private float startTime;
private bool finished = false;
private bool started = false;
void Update()
{
if (finished)
return;
if (started)
{
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
}
}
public void Finish()
{
finished = true;
timerText.color = Color.yellow;
}
void Start()
{
started = true;
}
}
答案 0 :(得分:1)
您可以执行与bool finished
相同的操作,但是它将类似于bool started
,当玩家进入启动触发器时,它将返回true。将其包装在Update()
语句中随时间变化的代码中。
确保Timer中的布尔对象是公开的:
public Text timerText;
public bool finished = false;
public bool started = false;
private float t = 0f;
void Update()
{
if (finished)
return;
if (started)
t += Time.deltaTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
}
void Started()
{
started = true;
}
然后在触发脚本中,引用连接到Player的Timer。
public class StartTrigger : MonoBehaviour
{
private GameObject player;
private Timer timer;
void Start()
{
player = GameObject.FindWithTag("Ellen");
if (player)
timer = player.GetComponent<Timer>();
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Ellen")
{
timer.Started();
}
}
}