Quantcast
Viewing all articles
Browse latest Browse all 103

Unity Freezing with for loop and prefab referencing

My main objective is to spawn some prefabs objects every couple of seconds from another prefab and have the spawned prefab travel to a set destination. I am using invokeRepeating to spawn them every couple of seconds. I am using a For Loop to go through each element in a list and test whether or not they are greater than or equal to 50. if condition is true then the for loop will instantiate the prefab and will also pass the i value to a variable in the newly spawned prefab script I am instantiating (i = factionNumber;). the variable listNumber in the spawned prefab script is an int that I am using to represent an element. the problem is that it completely freezes Unity. Any help would be appreciated. I am somewhat new to using loops so if there is a better way to accomplish this please let me know. Thanks in advance! P.S. i = tradeShipScript.listNumber; is causing the freezing. public class TradingAndTradeShips : MonoBehaviour { public List factionRelationship = new List(); public NeutralAIMovement tradeShipScript; public GameObject tradeShip; public float waitToSpawn; public int factionNumber; void Start () { factionNumber = 0; InvokeRepeating("spawnTradeShip", 0, waitToSpawn); } void spawnTradeShip() { for (int i = 0; i < factionRelationship.Count; i++) { if (factionRelationship[i] >= 50f) { GameObject tradeObj = Instantiate(tradeShip, new Vector3(transform.position.x, transform.position.y, tradeShip.transform.position.z), tradeShip.transform.rotation); i = factionNumber; } } } public class NeutralAIMovement : MonoBehaviour { public List tradeEndPointList = new List(); public PlayerMovement player; public TradingAndTradeShips homeRelationship; public int listNumber; public float speed; void Start () { listNumber = homeRelationship.factionNumber; } void Update () { transform.position = Vector2.MoveTowards(transform.position, tradeEndPointList[listNumber].position, speed * Time.fixedDeltaTime); } }

Viewing all articles
Browse latest Browse all 103

Trending Articles