- Home /
How to insert webRequest data to prefabs before instantiation
I have a script in which I want to inject data to several prefabs before I instantiate them. my idea was to make a "for" loop in which every time I send a url from a url list (string) and inject the response into the sprite list (later on there will also be additional data) and then instantiate. The problem is- unity doesn't wait for a response, so I get empty prefabs. I tried this: [SerializeField] GameObject prefab, container; public int amount = 10; private GameObject PowerBG, StaminaBG; public Sprite[] images; public string[] imagesURL;
void Start()
{
foreach (Transform child in transform)
{
GameObject.Destroy(child.gameObject);
}
for (int i = 0; i < amount; i++)
{
WebRequest.GetTexture(imagesURL[i], (string error) =>
{ //error
Debug.Log("Error: " + error);
},
(Texture2D texture2D) =>
{//successfuly contacted url
Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0, 0));
prefab.transform.Find("Avatar").GetComponent<Image>().sprite = sprite;//get image from Server
prefab.transform.Find("Name").GetComponent<TextMeshProUGUI>().text = "test " + (i).ToString();//get name from server
PowerBG = prefab.transform.Find("PowerBG").gameObject;
StaminaBG = prefab.transform.Find("StaminaBG").gameObject;
PowerBG.transform.Find("FillPower").GetComponent<Image>().fillAmount = .5f;
StaminaBG.transform.Find("FillStamina").GetComponent<Image>().fillAmount = .5f;
Instantiate(prefab, container.transform.position, Quaternion.identity, container.transform);
}
);
}
}
}
but all prefabs are appearing with the same name. I would really appreciate some help :)
Thanks!
Answer by liordizdar · May 09 at 08:05 AM
Okay, so i found a workaround: (it might not be perfect, but it works, id still be happy to learn how to properly build it)
I put a web request script on the prefab itself, and when I instantiate it I immediately inject it with the URL. and then each prefab receives its own response on its own free time.
Your answer
Follow this Question
Related Questions
[C#] How can I destroy instantiated prefabs when many are created with the same name? 2 Answers
Updating a variable on a script in an instanced object 1 Answer
Why is instantiated animator prefabs are not working properly? 2 Answers
[UNET] How to know the connectionID of a player ? 2 Answers
Instantiate object 1 Answer