根据您在Unity中查看对象的时间重置计时器

时间:2013-10-17 14:32:13

标签: c# timer unity3d

我在Unity中设置了光线投射,可以检测基于对象标记的对象。现在,我正在尝试做的是有一个定时事件,当我在标记对象看了一段时间后触发,然后,当我看向别处时,我希望定时器重置。

然而,我在实现这项工作时遇到了一些麻烦。有人可以看看我的代码,并指出我做错了什么?

public float end_time = 10.0f;
public float start_time;

// Use this for initialization
void Start () 
{
    start_time = Time.deltaTime;
}

// Update is called once per frame
void Update () 
{

    EyeTarget();
}

void EyeTarget()
{
    RaycastHit hit;
    Vector3 fwd = transform.TransformDirection(Vector3.forward);
    if (Physics.Raycast(transform.position, fwd, out hit))
    {
     //  Debug.Log("ray hit (tag): " + hit.collider.gameObject.tag + " : ");
        if(hit.collider.gameObject.tag == "floor")
        {
            Debug.Log("Just hit the floor");

            start_time = Time.time - end_time;
            if(start_time <= 0)
            {
                Debug.Log("looked at floor for 10 seconds");
            }
        }

        if( hit.collider.gameObject.tag != "floor")
        {
            ResetTimer();

        }
    }
    Debug.DrawRay(transform.position, fwd, Color.green);
}

void ResetTimer()
{
    start_time = Time.time;
    Debug.Log("resetting timer");
}

1 个答案:

答案 0 :(得分:0)

请问我尝试使用稍微不同的方法:

    public float end_time = 10.0f;
    public float start_time;
    private float running_time;

    // Use this for initialization
    void Start () 
    {
        start_time = Time.deltaTime;
        running_time = 0f;
    }

    // Update is called once per frame
    void Update () 
    {

        EyeTarget();
    }

    void EyeTarget()
    {
        RaycastHit hit;
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, fwd, out hit))
        {
         //  Debug.Log("ray hit (tag): " + hit.collider.gameObject.tag + " : ");
            if(hit.collider.gameObject.tag == "floor")
            {
                Debug.Log("Just hit the floor");

                start_time = Time.time - end_time;
                running_time += Time.deltaTime
                //if(start_time <= 0)
                if ( running_time >= end_time )
                {
                    Debug.Log("looked at floor for 10 seconds");
                }
            }

            if( hit.collider.gameObject.tag != "floor")
            {
                ResetTimer();

            }
        }
        Debug.DrawRay(transform.position, fwd, Color.green);
    }

    void ResetTimer()
    {
        start_time = Time.time;
        running_time = 0f;
        Debug.Log("resetting timer");
    }