Hello!
I found a inventory script on Youtube (link).
I added some functions and fixed some problems,
but there is one problem left.
I searched for the “error” for days. Until now i can only
delimit the problem. I think i need some help.
Mainly this script got two for - loops within one if statement.
I have remove the if from both for loops and change it also
into a for loop and insert it after both for loops.
I think i didn’t change the script noticeable but now
I can’t create the inventory two times.
(there is a button and a start void which start the CreateInventory void)
Original (the item added to the prefab while both for loops (for loops create all slots))
Original Scriptpart
public void CreateInventory()
{
foreach(Transform t in this.transform){
Destroy(t.gameObject);
}
for (int x = 1; x <= invetorySize.x; x++) {
for(int y = 1; y <= invetorySize.y; y ++){
GameObject slot = Instantiate(slotPrefab) as GameObject;
slot.transform.SetParent(this.transform);
slot.name = "slot_"+x+"_"+y;
slot.GetComponent<RectTransform>().anchoredPosition = new Vector3(windowSize.x/(invetorySize.x+1)*x, windowSize.y / (invetorySize.y+1) * -y);
//print ("hello "+GameDB.sortedItems.Count);
if((x + (y - 1)*4) <= GameDB.sortedItems.Count){
GameObject item = Instantiate(itemPrefab) as GameObject;
item.transform.SetParent(slot.transform);
item.GetComponent<RectTransform>().anchoredPosition = Vector3.zero;
Item i = item.GetComponent<Item>();
//ITEM COMPONENT VARIABLES
i.name = GameDB.sortedItems[(x + (y - 1)*4) - 1].name;
i.type = GameDB.sortedItems[(x + (y - 1)*4) - 1].type;
i.sprite = GameDB.sortedItems[(x + (y - 1)*4) - 1].sprite;
item.name = i.name;
item.GetComponent<Image>().sprite = i.sprite;
}
}
}
}
public void CreateInventory()
{
foreach(Transform t in this.transform){
Destroy(t.gameObject);
}
for (int x = 1; x <= invetorySize.x; x++) {
for(int y = 1; y <= invetorySize.y; y ++){
GameObject slot = Instantiate(slotPrefab) as GameObject;
slot.transform.SetParent(this.transform);
slot.name = "slot_"+(x + (y -1) * 4); //rename
slot.GetComponent<RectTransform>().anchoredPosition = new Vector3(windowSize.x/(invetorySize.x+1)*x, windowSize.y / (invetorySize.y+1) * -y);
// remove if
}
}
// if into for
for (int f = 1; f <= GameDB.sortedItems.Count; f++) {
GameObject item = Instantiate(itemPrefab) as GameObject;
item.transform.SetParent(GameObject.Find("slot_"+f).transform); //changing path
item.GetComponent<RectTransform>().anchoredPosition = Vector3.zero;
Item i = item.GetComponent<Item>();
i.name = GameDB.sortedItems[(f - 1)].name;
i.type = GameDB.sortedItems[(f - 1)].type;
i.sprite = GameDB.sortedItems[(f - 1)].sprite;
item.name = i.name;
item.GetComponent<Image>().sprite = i.sprite;
}
}
So why the whole functionality die after my “if into for” - transformation?
I hope you get enough infromation the help me.
(alternative i search for good inventory scripts for free)
have a good day!