目前我正在使用Unity和虚拟现实工具包(VRTK)开展项目。我想记录抓取对象的时间(用户抓取对象多长时间)。
到目前为止,我得到了这个:
using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VRTK;
public class System_2_Script_Slider_X : MonoBehaviour
{
float Timer;
void Start()
{
Timer = 0;
if (GetComponent<VRTK_InteractableObject>() == null)
{
Debug.LogError("Team3_Interactable_Object_Extension is required to be attached to an Object that has the VRTK_InteractableObject script attached to it");
return;
}
GetComponent<VRTK_InteractableObject>().InteractableObjectGrabbed += new InteractableObjectEventHandler(ObjectGrabbed);
GetComponent<VRTK_InteractableObject>().InteractableObjectUngrabbed += new InteractableObjectEventHandler(ObjectUngrabbed);
}
private void ObjectGrabbed(object sender, InteractableObjectEventArgs e)
{
//Some Code
Timer += Time.deltaTime;
}
private void ObjectUngrabbed(object sender, InteractableObjectEventArgs e)
{
//Some Code
File.AppendAllText("PATH/Timer.txt", Timer.ToString());
Timer = 0;
}
}
不幸的是,即使我抓住对象的时间更长,这也不会有大约2毫秒的时间。所以似乎ObjectGrabbed()
函数启动计时器但立即停止它。
我该如何解决这个问题?
答案 0 :(得分:3)
对象抓取功能可能只调用一次(当你抓住时)。
它不启动计时器,只是将自上一帧以来的时间添加到变量中。如果仅调用一次,则只会将一帧的时间添加到Time
变量。
你应该做的是在抓取对象>>时注册,这样你就可以计算释放它时的总长度:
using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VRTK;
public class System_2_Script_Slider_X : MonoBehaviour
{
private float _timeWhenGrabbed;
void Start()
{
if (GetComponent<VRTK_InteractableObject>() == null)
{
Debug.LogError("Team3_Interactable_Object_Extension is required to be attached to an Object that has the VRTK_InteractableObject script attached to it");
return;
}
GetComponent<VRTK_InteractableObject>().InteractableObjectGrabbed += new InteractableObjectEventHandler(ObjectGrabbed);
GetComponent<VRTK_InteractableObject>().InteractableObjectUngrabbed += new InteractableObjectEventHandler(ObjectUngrabbed);
}
private void ObjectGrabbed(object sender, InteractableObjectEventArgs e)
{
//Some Code
_timeWhenGrabbed = Time.time;
}
private void ObjectUngrabbed(object sender, InteractableObjectEventArgs e)
{
//Some Code
var grabDuration = Time.time - _timeWhenGrabbed;
File.AppendAllText("PATH/Timer.txt", grabDuration.ToString());
}
}
答案 1 :(得分:2)
ObjectGrabbed
方法可能仅在Grab
操作发生时被触发,而不是每个帧都被抓取。
因此,您应该使用一些Timer
或StopWatch
设置代码(秒表具有更高的精度)。
通过将计时器启动到ObjectGrabbed
方法并将计时器停止到ObjectUngrabbed
方法
像这样:
using System.Diagnostic.Stopwatch;
...
private StopWatch Watcher = new StopWatch();
...
private void ObjectGrabbed(object sender, InteractableObjectEventArgs e)
{
Watcher.Start();
}
private void ObjectUngrabbed(object sender, InteractableObjectEventArgs e)
{
Watcher.Stop();
long millis = Watcher.ElapsedMilliseconds;
Watcher.Reset();
File.AppendAllText("PATH/Timer.txt", millis.ToString());
}