- Home /
how can i make this code more efficient for my inventory system
This is for an inventory system i need help converting some code to make it go through a for loop and make the slots based on a pre defined number of slots
GUI.Box(Rect(SlotOne),"1");
GUI.Box(Rect(SlotTwo),"2");
GUI.Box(Rect(SlotThree),"3");
GUI.Box(Rect(SlotFour),"4");
GUI.Box(Rect(SlotFive),"5");
GUI.Box(Rect(SlotSix),"6");
GUI.Box(Rect(SlotSeven),"7");
GUI.Box(Rect(SlotEight),"8");
thats just for the quick slots now i want the inventory to be like minecraft and writing out the boxes one by one will take too long
thanks
Answer by Azrapse · Nov 07, 2013 at 01:18 PM
I'm not proficent at UnityScript, but I have tried to translate it by checking the reference manual. Please, be aware of possible minor syntax errors.
import System.Linq;
var slots : Rect[];
var slotCount: int;
function Start()
{
var halfCount = slotCount/2;
slots = Enumerable.Range(0, slotCount)
.Select(function(i)
Rect((Screen.width/ 2) + (i-halfCount)*100 * Xratio,
Screen.height / 2 + 450.0 * Yratio, 82.0 * Xratio, 82.0 * Yratio)
)
.ToArray();
}
function OnGUI()
{
for(int i=0; i<slots.Length; i++)
{
GUI.Box(slots[i], (i+1).ToString());
}
}
Built for C#,
using UnityEngine;
using System.Collections;
sealed class Inventory : $$anonymous$$onoBehavior
{
protected Rect[] slots = {};
private void Start()
{
slots = { SlotOne, SlotTwo, SlotThree, SlotFour, SlotFive, SlotSix, SlotSeven, SlotEight };
}
public void OnGUI()
{
for(Rect i in slots)
{
GUI.Box(new Rect(i), i.ToString());
}
}
}
Are you using a for ins$$anonymous$$d of a foreach there? Also, in that case i.ToString() won't show a number, but a rectangle data.
thanks for the answer, @Azapse yes its for the sizes and position
this is the calculations of positions and sizes for the hotbar
SlotOne = Rect((Screen.width/ 2) - 400 Xratio, Screen.height / 2 + 450.0 Yratio, 82.0 Xratio, 82.0 Yratio);
SlotTwo = Rect((Screen.width/ 2) - 300 * Xratio,
Screen.height / 2 + 450.0 * Yratio, 82.0 * Xratio,
82.0 * Yratio);
SlotThree = Rect((Screen.width/ 2) - 200 * Xratio,
Screen.height / 2 + 450.0 * Yratio, 82.0 * Xratio,
82.0 * Yratio);