将unity中相机位置保存为json 文件或者 发送给后端

将unity中相机位置保存保存到服务器

///相机的位置
 public Transform cameraTransform;

 void Start()
    {
       // SaveCameraPosition("sd");
        // ("{\"name\":\"sd\",\"position\":\"(0.00, 5.00, -12.00)\",\"rotation\":\"(25.00, 0.00, 0.00)\"});
      
    }
 ///保存数据
 public void SaveCameraPosition(string viewname)
    {
        if (!string.IsNullOrEmpty(viewname))
        {
            CameraView cameraView = new CameraView();
            cameraView.name = viewname;
            cameraView.position = cameraTransform.position.ToString();
            cameraView.rotation = cameraTransform.rotation.eulerAngles.ToString();
            string oko = JsonUtility.ToJson(cameraView);
            Application.ExternalCall("ReciveViwe", oko.ToString()) ;
        }
    }
    ///解析数据
      public void ParsingCameraViewdata(string json)
    {
        CameraView jsonData = JsonMapper.ToObject<CameraView>(json);
        Debug.Log("pos:"+jsonData.position+"rot:"+ jsonData.rotation);
        Vector3 po = StringToVector3(jsonData.position);
        Vector3 ro = StringToVector3(jsonData.rotation);
        MaxCamera.instance_.ModelMove(po, Quaternion.Euler(ro.x, ro.y, 0), 0.5f);
        //  GameManager.Instance.SettingCamera(po, ro);
    }
    // 字符串转为 v3
    public Vector3 StringToVector3(string sVector)
    {
        // 移除字符串中的括号
        if (sVector.StartsWith("(") && sVector.EndsWith(")"))
        {
            sVector = sVector.Substring(1, sVector.Length - 2);
        }
        // 拆分字符串为单独的值
        string[] sArray = sVector.Split(',');
        // 创建Vector3并返回
        return new Vector3(
            float.Parse(sArray[0]),
            float.Parse(sArray[1]),
            float.Parse(sArray[2]));
    }

 public class CameraView
    {
        public string name;
        public string position;
        public string rotation;
    }

将相机位置保存为json

using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
/// <summary>
/// 保存数据为json
/// </summary>
public class CameraSaveLoad : MonoSingleton<CameraSaveLoad>
{
    public Transform cameraTransform; // 相机的Transform组件
    public string saveFileName = "camera_view.json"; // 保存文件的名称
    public InputField viewNameInput; // 用于输入视角名称的UI InputField
    public Button surebtn;
    public Dictionary<string, CameraView> CamerViewDic = new Dictionary<string, CameraView>();
    // Start is called before the first frame update
    void Start()
    {
        LoadDeviceDic();
       
        surebtn.onClick.AddListener(SaveCameraPosition);
    }
    public class CameraView
    {
        public string name;
        public string position;
        public string rotation;
    }
    /// <summary>
    /// 解析数据 字符串转v3
    /// </summary>
    /// <param name="sVector"></param>
    /// <returns></returns>
   public Vector3 StringToVector3(string sVector)
    {
        // 移除字符串中的括号
        if (sVector.StartsWith("(") && sVector.EndsWith(")"))
        {
            sVector = sVector.Substring(1, sVector.Length - 2);
        }

        // 拆分字符串为单独的值
        string[] sArray = sVector.Split(',');

        // 创建Vector3并返回
        return new Vector3(
            float.Parse(sArray[0]),
            float.Parse(sArray[1]),
            float.Parse(sArray[2]));
    }
    public void SaveCameraPosition()
    {
        string viewName = viewNameInput.text;

        if (!string.IsNullOrEmpty(viewName))
        {
            CameraView cameraView = new CameraView
            {
                name = viewName,
                position = cameraTransform.position.ToString(),
                rotation = cameraTransform.rotation.eulerAngles.ToString()
            };
            AddCameratrToDic(viewName, cameraView);
        }
    }
/// 将数据保存为json
    public void AddCameratrToDic(string viewname, CameraView viewdate)
    {
        if (!CamerViewDic.ContainsKey(viewname))
        {
            CamerViewDic.Add(viewname, viewdate);
            SaveCamerViewDicTojson(CamerViewDic);
        }
        else
        {
            CamerViewDic[viewname] = viewdate;
            SaveCamerViewDicTojson(CamerViewDic);
        }
    }

    public void Delel()
    {
        // string filePath = Path.Combine(Application.streamingAssetsPath, "example.txt");

        string filePath = Path.Combine(Application.persistentDataPath, "camera_view.json");

        // 检查文件是否存在
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
            Debug.Log("文件已删除:" + filePath);
        }


    }

    public void SaveCamerViewDicTojson(Dictionary<string, CameraView> valuePairs)
    {
        JsonData jsonData = JsonMapper.ToJson(valuePairs);
        Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        var ss = reg.Replace(jsonData.ToString(), delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
        string filePath = Path.Combine(Application.streamingAssetsPath, "camera_view.json");
        File.WriteAllText(filePath, jsonData.ToString());
        Debug.Log("Dictionary data saved to: " + filePath);
    }
    public void LoadDeviceDic()
    {

        string filePath = Path.Combine(Application.streamingAssetsPath, "camera_view.json");
        //var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, "camera_view.json"));
        //UnityWebRequest request = UnityWebRequest.Get(uri);
        //yield return request.SendWebRequest();
        //if (request.isNetworkError)
        //{
        //    Debug.Log(request.error);
        //}
        //else
        //{
        //    string jsonStr = request.downloadHandler.text;
        //    CamerViewDic = JsonMapper.ToObject<Dictionary<string, CameraView>>(jsonStr);

        //    foreach (var pair in CamerViewDic)
        //    {
        //        Vector3 po = StringToVector3(pair.Value.position);
        //        Debug.LogError("po" + po.ToString());
        //        Debug.Log("Key: " + pair.Key + ", Value: " + pair.Value + ", " + pair.Value);
        //    }
        //}

         检查文件是否存在
        if (File.Exists(filePath))
        {
            // 从文件中读取 JSON 数据
            string json = File.ReadAllText(filePath);

            // 将 JSON 数据转换为字典
            CamerViewDic = JsonMapper.ToObject<Dictionary<string, CameraView>>(json);


            Debug.Log("Dictionary data loaded from: " + filePath);

            // 示例:输出加载的数据
            foreach (var pair in CamerViewDic)
            {
                Vector3 po = StringToVector3(pair.Value.position);
              //  Debug.LogError("po" + po.ToString());
                Debug.Log("Key: " + pair.Key + ", Value: " + pair.Value + ", " + pair.Value);
            }
        }
        else
        {
            Debug.LogError("Dictionary data file not found!");
        }
        // DeviceManager.GetInstance().myDictionary;
    }

   
}

相关推荐

  1. Unity 安卓数据保存json并读取

    2024-05-09 06:44:03       17 阅读
  2. mysql 字段类型json用list接收

    2024-05-09 06:44:03       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-09 06:44:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-09 06:44:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-09 06:44:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-09 06:44:03       20 阅读

热门阅读

  1. React 学习-3

    2024-05-09 06:44:03       7 阅读
  2. 001 websocket(评论功能demo)(消息推送)

    2024-05-09 06:44:03       10 阅读
  3. react 项目中使用 iconfont

    2024-05-09 06:44:03       11 阅读
  4. Kafka 环境搭建之伪分布式集群模式详细教程

    2024-05-09 06:44:03       12 阅读
  5. Jenkins的原理及应用详解(二)

    2024-05-09 06:44:03       10 阅读
  6. C++ Opencv之图像数据拷贝分析

    2024-05-09 06:44:03       11 阅读
  7. nodejs之log4js日志管理

    2024-05-09 06:44:03       13 阅读
  8. AR技术的那些事

    2024-05-09 06:44:03       10 阅读
  9. CUDA笔记

    2024-05-09 06:44:03       11 阅读
  10. uni-app 自定义tabbar

    2024-05-09 06:44:03       11 阅读