我有一个问题。我有 5 个表对象,它需要 5 个计时器,所以每个表 1 个计时器
我创建了一个名为 Table.cs
Table.cs
public UILabel info_timer = null;
我有我的主脚本,我们称它为 Main.cs
Main.cs
const float gap = 20.0f;
Table[] script_table;
bool start_timer = false;
int t_no;
public static string Ctimer = "";
void Update()
{
int i = returnTableNo(t_no);
if (i != -1 && script_tables != null && script_tables[i] != null)
{
gap -= Time.deltaTime();
if(gap <= 0.0f)
{
script_table[i].info_timer = Ctimer = "[808080]0[-]";
}
else
{
script_table[i].info_timer.text = gap.ToString("F0");
}
}
}
//someone will call this to make start_timer to true;
void ActivateTimer(){
t.tableno = t_no;
start_timer = true;
}
//this line of code is for the table no == table no
int returnTableNo(int table_no)
{
//table is equavalent to 5 for now
for (int i = 0; i < table.Count; i++)
{
if (t.table_no == table_no)
{
return i;
}
}
return -1;
}
现在我很困惑如何将每个计时器放在我拥有的每张 table 上。因为我遇到的情况是例如
表 1 正在运行,只有表 1 计时器将是唯一一个启动计时器的人,但发生的情况是所有表计时器都在运行,即使我的一些表没有运行。
他的命令被调用时他们正在运行
GCommand.start_:
这是一张图,您可以想象我正在尝试做什么。
感谢愿意帮助我的人。
最佳答案
您可以将计时器功能放在两个(通常)位置之一。第一个在您的 Main.cs 中,第二个在您的 Table.cs 中。每种方法都有优点和缺点。我的偏好是修改 Table.cs 以基本上允许使用任何一种样式,但以下示例倾向于在每个表中进行所有处理。
使用Table.cs封装功能示例:
// If Table.cs is derived from MonoBehaviour, the Update() method can be
// used to drive the timer. But adds the inherit overhead of being a MonoBehaviour.
public class Table : MonoBehaviour
{
public UILabel info_timer = null;
const float gap = 20.0f;
private float timer;
public bool isActive { get; private set; } = false;
public void ActivateTimer( bool activate = true)
{
// If activate is true, then reset this timer to the default.
if ( activate )
timer = gap;
isActive = activate;
}
// Use Update to drive the timer from each components Update call? Ignored if this class does not derive from MonoBehaviour.
public void Update()
{
UpdateTimer(Time.deltaTime);
}
// Use an explicit update method to drive the timer.
public void UpdateTimer( float deltaTime)
{
// We can even check to see if the table is active or the timer has already timed out.
if ( !isActive ) return;
timer -= deltaTime;
if ( timer <= 0.0f )
{
script_table[i].info_timer = Ctimer = "[808080]0[-]";
isActive = false;
}
else
script_table[i].info_timer.text = gap.ToString("F0");
}
}
使用 Main.cs 驱动所有表的所有更新,而不是表更新方法:
public class Main : MonoBehaviour
{
const float gap = 20.0f;
Table[] script_table;
bool start_timer = false;
int t_no;
public static string Ctimer = "";
public void Update()
{
for ( int i = 0; i < script_table.Length; i++ )
script_table[i].UpdateTimer(Time.deltaTime);
}
// This method can now be used to Activate or De-Activate a timer.
public void ActivateTimer ( int tableNumber, bool activate = true )
{
script_table[tableNumber ].ActivateTimer( activate );
}
}
关于c# - 动态实例化 5 个表的 5 个计时器(UNITY 3D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354220/