- Home /
Error with picking up an item...
I have a "for" loop that should give the user an item. I have the inventory scripts set up already, everything in good order. However, I do not know how to add the item to the inventory when the player presses "E" and the mouse cursor is over the item (cursor locked in screen center and cross-hair set up).
for(var x = 0; x < loot.length; x++) {
Inventory.playerInventory.Add(loot[x]);
}
Can anyone help me? Do I use OnMouseEnter?
Thanks in advance!
Are you trying to accomplish this in a GUI or in 3D space?
The picking up of an item is in 3D space, with a script to destroy the object after it is used. But I cannot use On$$anonymous$$ouseOver, because this looting method is already a function itself, and cannot be used within another function. Here is the code:
#pragma strict
var loot : ItemClass[];
var Inventory : Inventory;
function Start () {
}
function Update () {
}
function Giveloot() {
for(var x = 0; x < loot.length; x++) {
Inventory.playerInventory.Add(loot[x]);
}
}
And my Inventory Script:
#pragma strict
import System.Collections.Generic;
var playerInventory : List.<ItemClass> = new List.<ItemClass>();
var scrollView : Vector2;
var equippedItem : ItemClass;
var equipped : boolean = false;
var playerHand : Transform;
function Update () {
if(equippedItem.itemType == ItemClass.ItemType.Weapon) {
equipped = true;
}
else {
equipped = false;
}
}
function OnGUI() {
//INVENTORY
GUILayout.BeginArea(Rect(Screen.width - 500, 0, 500, 500));
scrollView = GUILayout.BeginScrollView(scrollView, GUILayout.Width(500), GUILayout.Height(500));
for(var x = 0; x < playerInventory.Count; x++) {
GUILayout.BeginHorizontal();
if(GUILayout.Button(playerInventory[x].icon) && playerInventory[x].itemType == ItemClass.ItemType.Weapon && equipped == false) {
equippedItem = playerInventory[x];
var weapon : Transform = Instantiate(playerInventory[x].itemPrefab, playerHand.position, Quaternion.identity);
weapon.parent = playerHand;
playerInventory.RemoveAt(x);
return;
}
GUILayout.Box(playerInventory[x].name);
GUILayout.EndHorizontal();
GUILayout.Box(playerInventory[x].description);
}
GUILayout.EndScrollView();
GUILayout.EndArea();
//WEAPON SLOT
if(GUI.Button(Rect(Screen.width / 2 - 25, Screen.height - 50, 50, 50), equippedItem.icon) && equipped == true) {
playerInventory.Add(equippedItem);
Destroy(GameObject.FindGameObjectWithTag("Weapon"));
equippedItem = new ItemClass();
}
}
Hope this comes in any use to you guys.
Answer by MikeNewall · Feb 23, 2013 at 10:54 PM
OnMouseOver() Is triggered when you mouseover an objects collider or a gui element.
function OnMouseOver()
{
if(Input.GetKeyDown("e"))
{
//Do your inventory stuff here
}
}