将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;
    }

   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值