Unity开发——GameObject计时器

本文介绍了一种在Unity中为每个GameObject实现独立计时器的方法。通过创建TimeCount和TimeObject两个类,实现了GameObject上的时间管理和控制功能。TimeCount类负责计时逻辑,而TimeObject类则用于绑定GameObject和计时器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity:2021.1.14flc1
在UnityAR开发的过程中,需要给每一个我生成的GameObject加一个单独的计时器对其进行控制,我写了两个类,TimeCount(计时器)和TimeObject(带计时器的GameObject),在主控件的Update()中,利用TimeOn(int a)函数逐帧的计算时间,并且利用其中的a变量做倍速效果

TimeCount

public class TimeCount
{
    private float timer = 0f;
    public float Timer { get { return timer; } set { timer = value; } }
    public int H { get { return h; } set { h = value; } }
    public int M { get { return m; } set { m = value; } }
    public int S { get { return s; } set { s = value; } }
    private int h = 0;
    private int m = 0;
    private int s = 0;

    // Update is called once per frame
    public void TimeOn(int a)
    {
        timer += Time.deltaTime*a*1f;
        if (timer >= 1f)
        {
            s++;
            timer = 0;
        }
        if (s >= 60)
        {
            m++;
            s = 0;
        }
        if (m >= 60)
        {
            h++;
            m = 0;
        }
        if (h >= 99)
        {
            h = 0;
        }
    }

    public void TimeStop()
    {
        h = 0;
        m = 0;
        s = 0;
    }
}

TimeObject

public class TimeObject
{
    /// <summary>
    /// 种植物模型对象
    /// </summary>
    public GameObject Plant;
    /// <summary>
    /// 计时器
    /// </summary>
    public TimeCount Time
    {
        get
        {
            return time;
        }
        set
        {
            time = value;
        }
    }
    /// <summary>
    /// 计时器
    /// </summary>
    private TimeCount time;

    public TimeObject(GameObject Plant)
    {
        this.Plant = Plant;
        time = new TimeCount();
    }

    public TimeObject()
    {
        Plant = new GameObject();
        time = new TimeCount();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值