目前我正在使用 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()
函数启动计时器但立即停止它。
我该如何解决这个问题?
最佳答案
对象抓取函数可能只调用一次(当您抓取时)。
它不会启动计时器,它只是将自上一帧以来的时间添加到您的变量中。如果只调用一次,它只会将一帧的时间添加到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());
}
}
关于c# - 如何获得物体被抓取多长时间的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49301625/