我想使用某些设备移动立方体,并定期(每3秒)将这些坐标打印到文件中。我不确定如何使用下面的代码来完成此操作。有人对如何做到这一点有想法吗?
谢谢!
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
[RequireComponent(typeof(MeshCollider))]
public class UserController : MonoBehaviour {
public int speed = 20;
// Update is called once per frame
void Update()
{
// get input data from keyboard or controller
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// update player position based on input
Vector3 position = transform.position;
position.x += moveHorizontal * speed * Time.deltaTime;
position.z += moveVertical * speed * Time.deltaTime;
transform.position = position;
}
void OnMouseDrag()
{
if(Input.GetMouseButton(0))
{
float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance_to_screen));
}
}
}
答案 0 :(得分:1)
我建议创建一个单独的脚本并将其附加到您的多维数据集。
public class CubeTracker : MonoBehaviour
{
private bool logging = true;
void Awake()
{
StartCoroutine(LogPosition());
}
private IEnumerator LogPosition()
{
while (logging)
{
Debug.Log(transform.position);
yield return new WaitForSeconds(3f);
}
}
}
这将在创建多维数据集后立即启动协程,并将您所需的结果记录到控制台中。如果这是您想要的,则可以继续,并用写入文件的实现替换Debug.Log。
答案 1 :(得分:0)
使用全局变量,并将其输入Update()
方法中。
例如:
private Vector3 LastCoordinate{get; set;}
,并使用像这样的定期计时器:
private System.Threading.Timer timer;
timer = new System.Threading.Timer(GetLastCoordinate, null, 3000, 0);
private void GetLastCoordinate()
{
lock(this)
{
Vector3 lastCoordEachThreeSecs = LastCoordinate;
}
}