以指定的时间间隔将 Unity 坐标打印到字符串

我想使用某些设备移动立方体并定期(每 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));

        }

    }

}


慕田峪4524236
浏览 216回答 2
2回答

江户川乱折腾

我建议创建一个单独的脚本并将其附加到您的多维数据集。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 替换为写入文件实现。

泛舟湖上清波郎朗

使用全局变量,并在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;    }}
打开App,查看更多内容
随时随地看视频慕课网APP