gpt4 book ai didi

c# - Unity如何使用从json字符串加载的变量作为更新部分的输入

转载 作者:行者123 更新时间:2023-12-05 06:52:50 25 4
gpt4 key购买 nike

一般来说,我对 Unity 和 C# 编码还很陌生,所以我的问题对你们中的一些人来说可能很愚蠢,但我目前正在尝试在其坐标来自 json 字符串的位置创建一个按钮。我只是不知道从这里下一步该去哪里来实现我的目标。如何使用 json 中的 xcoor 作为更新的输入?这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using SimpleJSON;

public class JSONcontroller : MonoBehaviour
{
public GameObject obj;
Vector3 buttonPos;
private string url = "http://localhost:3000/coordinates/";

// Start is called before the first frame update
void Start()
{
StartCoroutine(getData());

}

IEnumerator getData()
{
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if(request.isNetworkError||request.isHttpError)
{
Debug.LogError(request.error);
yield break;
}
JSONNode coordinates = JSON.Parse(request.downloadHandler.text);
string xcoor = coordinates["x1"];
string ycoor = coordinates["y1"];
//Debug.Log(xcoor);


}

// Update is called once per frame
void Update()
{
buttonPos = new Vector3(xcoor, ycoor, 4f);
if (Input.GetButton("Fire1"))
Instantiate(obj, buttonPos, Quaternion.identity);
}
}

和我的示例 json 文件

{
"coordinates": [
{
"id": 1,
"x1": "5",
"y1": "2"
},
{
"id": 2,
"x1": "3",
"y1": "5"
},
{
"id": 3,
"x1": "5",
"y1": "7"
}
]
}

最佳答案

您的“xcoor”和“ycoor”变量实际上是在您的 getData() 方法中声明的,这意味着这些变量只能在方法 getData() 中使用。

您可以在类的顶部声明它们,然后您就可以在更新中使用变量并设置按钮位置。

编辑代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using SimpleJSON;

public class JSONcontroller : MonoBehaviour
{
public GameObject obj;
Vector3 buttonPos;
private string url = "http://localhost:3000/coordinates/";
string xcoor;
string ycoor;

// Start is called before the first frame update
void Start()
{
StartCoroutine(getData());

}

IEnumerator getData()
{
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if(request.isNetworkError||request.isHttpError)
{
Debug.LogError(request.error);
yield break;
}
JSONNode coordinates = JSON.Parse(request.downloadHandler.text);
xcoor = coordinates["x1"];
coor = coordinates["y1"];
//Debug.Log(xcoor);


}

// Update is called once per frame
void Update()
{
buttonPos = new Vector3(xcoor, ycoor, 4f);
if (Input.GetButton("Fire1"))
Instantiate(obj, buttonPos, Quaternion.identity);
}
}

关于c# - Unity如何使用从json字符串加载的变量作为更新部分的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65898365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com