Я пытаюсь создать экземпляр GameObject с помощью сценариев в проекте Unity.Проблема заключается в том, что при его выполнении в Unity он начинает создавать бесконечные клоны префаба.
Это MonumentFactory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json.Linq;
public class MonumentFactory : MonoBehaviour
{
// Class to handle monuments information
public class Monumento
{
public string nombre;
public int codvia;
public double[] coordinates;
}
// List of loaded monuments
public List<Monumento> Monumentos;
// UTM center value
public double[] utmCenter = { 721441.668, 4376931.207 };
// 3D representation of each monument
public GameObject MonumentPrefab;
// URL to download monuments information
public string url = "http://mapas.valencia.es/lanzadera/opendata/Monumentos-turisticos/JSON";
// Start is called before the first frame update
void Start()
{
// Load monuments JSON
StartCoroutine(GetRequest(url));
}
IEnumerator GetRequest(string url)
{
// Create web request
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
// Request and wait for the desired content
yield return webRequest.SendWebRequest();
// Check errors
if (webRequest.isNetworkError)
{
Debug.LogError("Error loading monuments: " + webRequest.error);
}
else
{
Monumentos = new List<Monumento>();
// Parse JSON
JObject todo = JObject.Parse(webRequest.downloadHandler.text);
foreach (JObject m in todo["features"])
{
Monumento monumento = m["properties"].ToObject<Monumento>();
monumento.coordinates = m["geometry"]["coordinates"].ToObject<double[]>();
Monumentos.Add(monumento);
// Debug information
Debug.Log(monumento.nombre + " " + (monumento.coordinates[0] - utmCenter[0]) + " " + (monumento.coordinates[1] - utmCenter[1]));
// Create position acording to UTM center
Vector3 pos = new Vector3(
(float)(monumento.coordinates[0] - utmCenter[0]),
0,
(float)(monumento.coordinates[1] - utmCenter[1]));
// Create the 3D representation of the monument in its 3D position
GameObject aux = Instantiate(
MonumentPrefab,
pos,
Quaternion.identity
// transform
);
// Set monument information, in this case only the name
aux.GetComponent<Monument>().label.text = monumento.nombre;
Debug.Log(aux.GetComponent<Monument>());
}
}
}
}
}
А это Monumnet.cs
using System.Collections.Generic;
using UnityEngine;
public class Monument : MonoBehaviour
{
public TMPro.TextMeshPro label;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//Look always to the camera
transform.LookAt(Camera.main.transform, Vector3.up);
//Adjust size according to the distance from the camera
float dist = (transform.position - Camera.main.transform.position).magnitude;
float tam = 0.1f * dist;
transform.localScale = new Vector3(tam, tam, tam);
}
}
Я ожидаю создать экземпляр GameObject для каждого элемента из файла JSON.Есть предложения?