So i was following a tutorial and i made an inventory that opens and closes when i press i, the issue is it also opens and closes whenever i left mouse click and i don’t know why.
Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
public int SlotsX, SlotsY;
public GUISkin skin;
public List<Item> inventory = new List<Item>();
public List<Item> slots = new List<Item>();
private bool showInventory;
private ItemDatabase database;
private bool showTooltip;
private string tooltip;
private bool draggingitem;
private Item draggedItem;
// Use this for initialization
void Start () {
for (int i = 0; i < (SlotsX * SlotsY); i++)
{
slots.Add(new Item());
inventory.Add (new Item ());
}
database = GameObject.FindGameObjectWithTag("Item Database").GetComponent<ItemDatabase>();
AddItem(1);
AddItem(0);
RemoveItem (1);
print (InventoryContains (1));
}
void Update()
{
if (Input.GetButtonDown ("Inventory"))
{
showInventory = !showInventory;
}
}
void OnGUI ()
{
tooltip = "";
GUI.skin = skin;
if (showInventory)
{
DrawInventory ();
if (showTooltip)
GUI.Box (new Rect (Event.current.mousePosition.x + 15f, Event.current.mousePosition.y, 200, 200), tooltip, skin.GetStyle("Tooltip"));
}
if (draggingitem)
{
GUI.DrawTexture(new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 50, 50), draggedItem.itemIcon);
}
}
void DrawInventory()
{
Event e = Event.current;
int i = 0;
for (int y = 0; y < SlotsY; y++)
{
for (int x = 0; x < SlotsX; x++)
{
Rect slotRect = new Rect (x * 110, y * 110, 100, 100);
GUI.Box (slotRect, "", skin.GetStyle("Slot"));
slots _= inventory*;*_
_ if(slots*.itemName != null)
{
GUI.DrawTexture(slotRect, slots.itemIcon);
if (slotRect.Contains(e.mousePosition))
{
tooltip = CreateTooltip (inventory);
showTooltip = true;
if (e.button == 0 && e.type == EventType.MouseDrag)
{
draggingitem = true;
draggedItem = slots ;
}
}
}
if (tooltip == “”)
{
showTooltip = false;
}
i++;
}
}
}
string CreateTooltip(Item item)
{
tooltip = “<color=#ffffff>” + item.itemName + "
" +item.itemDesc;
return tooltip;
}*_
* void RemoveItem(int id)*
* {*
* for(int i = 0; i < inventory.Count; i++)*
* {*
_ if(inventory*.itemID == id)
{
inventory = new Item();
break;
}
}
}*_
* void AddItem(int id)*
* {*
* for (int i = 0; i < inventory.Count; i++)*
* {*
_ if (inventory .itemName == null)
* {
for (int j = 0; j < database.items.Count; j++)
{
if (database.items [j].itemID == id)
{
inventory = database.items [j];
}
}
break;
}
}
}*_
* bool InventoryContains(int id)*
* {*
* bool result = false;*
* for (int i = 0; i < inventory.Count; i++)*
* {*
_ result = inventory .itemID == id;
* if (result)
{
break;
}*_
* }*
* return result;*
* }*
}
I have no idea which part of the code is causing this, i just assumed Unity is assigning left mouse click to the function by default because it’s not used currently but now i came to the point where it actually is used for something else and the problem persists.