I have a simple inventory with 2 slots. In the “Inventory” script the slots are transform variables so Unity can get some info (like name) about the specific item that occupies a certain slot and each one has a boolean variable that shows wether the slots are used or not. I have another script called “Items” in which Unity parents the picked up item on a certain event(player presses the key “I” when in range) and changes the slots booelan variable in order to let other items occupy other slots. The problem is it doesn’t work.
Here’s the “Items” script:
- var Inventory:Transform;
- var player:Transform;
- var distance;
- var item=true;
- var pickingUp=false;
- var pickingUpDistance=5;
- var Name = “”;
- var pickedup=false;
- function Update () {
- if (item==true) {
- distance = Vector3.Distance(player.position, transform.position);
- if(distance < pickingUpDistance){
- pickingUp = true;
- }
- else{
- pickingUp = false;
- }
- }
- //if the player chooses to pick up item…
- if(pickingUp==true){
- if(Input.GetKeyDown(KeyCode.E)){
- MoveItemToPlayer();
- pickedup=true;
- }
- }
- //let’s find a free slot
- if(pickedup==true){
- if(Inventory.GetComponent(“Inventory”).slot1ocuppied==false){
- Inventory.GetComponent(“Inventory”).slot1 = GameObject.Find(Name).transform;
- Inventory.GetComponent(“Inventory”).slot1ocuppied=true;
- }
- else{
- if(Inventory.GetComponent(“Inventory”).slot1ocuppied==true){
- Inventory.GetComponent(“Inventory”).slot2 = GameObject.Find(Name).transform;
- Inventory.GetComponent(“Inventory”).slot2ocuppied=true;
- }
- }
- }
- }
- function MoveItemToPlayer()
- {
- transform.collider.isTrigger=true;
- transform.renderer.enabled=false;
- transform.parent = Inventory;
- transform.position = Inventory.transform.position;
- transform.rotation = Inventory.transform.rotation
- }
And here’s the “Inventory” script
-
var drawInventory=false;
-
var slot1:Transform;
-
var slot2:Transform;
-
var slot1occupied = false;
-
var slot2ocuppied = false;
-
function Update () {
-
if(Input.GetKeyDown(KeyCode.I)){
-
drawInventory=!drawInventory;
-
}
-
}
-
function OnGUI(){
-
if(!drawInventory)
-
return;
-
GUI.Button(Rect(100,175,100,50), “Inventory”);
-
GUI.Box(Rect(100,225,100,25), slot1.GetComponent(“ItemAttributes”).Name);
-
GUI.Box(Rect(100,250,100,25), slot2.GetComponent(“ItemAttributes”).Name);
-
}
-
//the script "ItemAttributes contains only one variable and it is attached to each
-
//item