从Unity游戏C#中的计时器中减去时间



最近,我一直在开发一款赛车游戏,该游戏要求玩家避开放射性桶,如果它们碰巧撞上,应该减去15秒;下面是我的"定时器"脚本和我的桶碰撞脚本的代码。

计时器脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{
public float timeRemaining = 10;
public bool timerIsRunning = false;
public Text timeText;

public void Start()
{
// Starts the timer automatically
timerIsRunning = true;
}

public void Update()
{
if (timerIsRunning)
{
if (timeRemaining > 0)
{
timeRemaining -= Time.deltaTime;
DisplayTime(timeRemaining);
}
else
{
Debug.Log("Time has run out!");
timeRemaining = 0;
timerIsRunning = false;
}
}
}

public void DisplayTime(float timeToDisplay)
{
timeToDisplay += 1;

float minutes = Mathf.FloorToInt(timeToDisplay / 60); 
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
}
}

接下来,是我的桶碰撞脚本:

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;    
public class ExplosionTrigger : MonoBehaviour 
{

public AudioSource ExplosionSound;
public ParticleSystem Explosion;

public void OnTriggerEnter(Collider collider)
{
Explosion.Play();
ExplosionSound.Play();
Timer.timeRemaining += 1.0f;      
}  
}

我有没有办法通过撞到Timer脚本中的Barrels来减去时间?

timeRemaining公开给其他类的最简单方法是使用static关键字。

public static float timeRemaining = 10;

通过使变量为静态,它可以被其他类引用。如果您不想完全公开变量,那么可以创建静态setter/getter。当使用setter/getter时,变量将是private static float timeRemaining = 10;

public static float TimeRemaining
{
get{ return timeRemaining;}
set { timeRemaining = value;}
}

如果你碰巧想从脚本中向类公开更多的变量或方法,我建议你要么实现Singleton模式,要么可能实现你自己的事件系统,它使用Singleton图案在你的项目中自由传递事件。通过这种方式,您可以订阅并激发要侦听的各种脚本的事件。

是的,您可以使用GetComponent<>()从不同的游戏对象访问脚本。你应该设置一个GameObject变量,并拖动带有脚本的游戏对象。将其添加到你的桶脚本中:

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;    
public class ExplosionTrigger : MonoBehaviour 
{

public AudioSource ExplosionSound;
public ParticleSystem Explosion;
public GameObject Timer;
public float timeLoss;
public Timer timer;
void Start()
{
timer = Timer.GetComponent<TimerScript>();
}
public void OnTriggerEnter(Collider collider)
{
timer.timeRemaining -= 1f;
Explosion.Play();
ExplosionSound.Play();
}  
}

您可以使用句点更改TimerScript中的值。请确保将TimerScript更改为Timer游戏对象上的脚本名称。

最新更新