I am trying to call a async function in loop to spawn object. it doesn't work as I expected. Dictionary is giving errors about adding same item multiple times. I can't make the whole function async. Here is the code:
public Dictionary_String_Prop GeneratePlaceables(List<PropData> props, Prop parent = null)
{
Dictionary_String_Prop temp = new Dictionary_String_Prop ();
if(props == null)
{
Debugger.Log("PropdataList Empty: Returning Empty Dictionary");
return temp;
}
for (int i = 0; i < props.Count; i++)
{
var result = GameModeGame.Get().placeableDB[props[i].dataID].Prefab;
PropData propData = props[i];
result.InstantiateAsync(props[i].sTransform.Position(), props[i].sTransform.Rotation()).Completed += a =>
{
Placeable p = a.Result.GetComponent<Placeable>();
p.uniqueID = propData.uniqueID;
p.State = propData.state;
p.InitData();
if(parent)
p.SetParent(parent);
else
p.transform.SetParent(manager.transform);
p.transform.localScale = propData.sTransform.Scale();
p.children = GeneratePlaceables(propData.placeables, p);
temp.DebugLog();
temp.Add(p.uniqueID, p);
manager.allProps.Add(p.uniqueID, p);
};
}
return temp;
}
I also tried to save all the instantiation task into an array and then use Task.WaitAll() to wait for thread to finish and then return from function but it also throws errors.
Question:- How can I instantiate every object asynchronously before exiting loop?