如何解决unity 如何使用从json字符串加载的变量作为更新部分的输入
总的来说,我对 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,"y1": "7"
}
]
}
解决方法
您的“xcoor”和“ycoor”变量实际上是在 getData() 方法中声明的,这意味着这些变量只能在方法 getData() 中使用。
您可以在类的顶部声明它们,然后您就可以使用Update中的变量并设置按钮位置。
编辑代码:
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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。