- Home /
Scripts freezes game for a few seconds after build.
Hello guys. Im working on Inventory. I have problem with game after build only. I have script for add items to slot.
public static void setInSlot(Item item)
{
for(int i = 0; i < playerItems.Count; i++)
{
if(playerItems[i].ID == item.itemID)
{
if(playerItems[i].amount < item.maxStack)
{
playerItems[i].amount++;
return;
}
}
}
for(int i = 0; i < Slots.Count; i++)
{
if(Slots[i].transform.childCount == 0)
{
GameObject itemObj = Instantiate(itemprf);
itemObj.name = item.itemID.ToString();
playerItems.Add(itemObj.GetComponent<itemObject>());
itemObj.GetComponent<itemObject>().ID = item.itemID;
itemObj.transform.SetParent(Slots[i].transform);
itemObj.GetComponent<Image>().sprite = item.itemSprite;
itemObj.transform.localPosition = Vector2.zero;
itemObj.transform.localScale = Vector3.one;
break;
}
}
}
There are 2 loops. 1st checks max stack of object. Second checks free slots to add items there. In editor everything works good. There are no freezes, no lags etc. Only after build I have problem with it. When I want to add item game get lag for 3/5 seconds. But freeze happens only one, first time. It looks that the script is loading for first time or something. So is any way to make this better? Or to fix that lags? Thank you in advance:)
Answer by FM-Productions · May 21, 2017 at 04:08 PM
Hi,
I have encountered something similar. In my case, it is almost certain to say that the first time a complex prefab is Instantiated will cause my game to lag. In your line 18, Instead of instantiating, you could make a pool of itemprf objects and maybe set them inactive. If you need a itemprf gameObject you simply take one from your pool and set the gameObject active. Another tip in terms of performance is to avoid functions like GetComponent in Update() functions (or functions that are executed often).
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Nested for-loop freezing Unity 0 Answers
Web Player occasionally lags browser 1 Answer
Help! Unsaved work stuck in frozen unity, believed to be from infinite loop. What can i do? 2 Answers
Unity 5 64x Build bug ? 1 Answer