Search Unity

Here is a drag and drop inventory

Discussion in 'Scripting' started by DexRobinson, Aug 1, 2011.

  1. DexRobinson

    DexRobinson

    Joined:
    Jul 26, 2011
    Posts:
    594
    So I been looking around the forms for a couples of days and still haven't seen anyone post anything about a drag and drop inventory system with a full set of code. So I figured it out and figured I would share it with everyone so they don't have to deal with look anything for days and days again so here you go...

    Code (csharp):
    1.  
    2. static var texture : Texture2D;
    3.  
    4. private var emptyTexture : Texture2D;
    5. private var windowRect: Rect = Rect(Screen.width / 2, Screen.height / 2, 420, 240);
    6. private var textureToAdd : Texture2D[,] = new Texture2D[4,4];
    7. private var textureListSize = 4;
    8.  
    9. function OnGUI()
    10. {
    11.     CreateEmptyInvetorySlots();
    12. }
    13.  
    14. function DragInventory(windowID:int)
    15. {
    16.     for(var x = 0; x < textureListSize; x++)
    17.     {
    18.         for(var y = 0; y < textureListSize; y++)
    19.         {      
    20.             var rect = Rect(100 * x + 10, 50 * y + 20, 100, 50);
    21.             var slot = GUI.Button(rect, textureToAdd[x,y]);
    22.            
    23.             if(rect.Contains(Event.current.mousePosition))
    24.             {
    25.                 if(textureToAdd[x,y] == null  Input.GetMouseButtonUp(0))
    26.                 {
    27.                     textureToAdd[x,y] = texture;
    28.                
    29.                     texture = null;
    30.                     AddToInventory.toolSelected = false;
    31.                 }
    32.                
    33.                 if(Input.GetMouseButtonUp(1))
    34.                 {
    35.                     textureToAdd[x,y] = null;
    36.                 }
    37.             }
    38.            
    39.             if(slot)
    40.             {
    41.                 // this is when each button gets pressed
    42.             }
    43.         }
    44.     }
    45.     GUI.DragWindow();
    46. }
    47.  
    48. function CreateEmptyInvetorySlots()
    49. {
    50.     GUI.BeginGroup(windowRect);
    51.     windowRect = GUI.Window(0, windowRect, DragInventory, "Inventory");
    52.     GUI.EndGroup();
    53. }
    54.  
    55.  
    56.  
    Code (csharp):
    1.  
    2. var textureToAdd : Texture2D;
    3.  
    4. static var toolSelected : boolean = false;
    5.  
    6. private var mouseDown : boolean = false;
    7.  
    8. function OnMouseDown()
    9. {
    10.     DragDrop.texture = this.textureToAdd;
    11.     toolSelected = true;
    12. }
    13.  
    14. function Update()
    15. {
    16.     if(Input.GetMouseButtonDown(0))
    17.         mouseDown = true;
    18.    
    19.     if(Input.GetMouseButtonUp(0)  mouseDown)
    20.         mouseDown = false;
    21.    
    22. }
    23. function OnGUI()
    24. {
    25.     if(toolSelected  mouseDown)
    26.     {
    27.         var mousePos : Vector3 = Input.mousePosition;
    28.         var pos : Rect = Rect(mousePos.x,Screen.height - mousePos.y, DragDrop.texture.width, DragDrop.texture.height);
    29.         GUI.Label(pos,DragDrop.texture);
    30.     }
    31. }
    32.  
    How you use this is you place the first script onto an empty game object in your scene. Then you put the other script onto a game object that you would like to be able to add to you inventory. All you need to add is your own icon for the object since this is what will show up on the screen to drag over.
     
  2. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    A very good start, thank you for sharing.
     
  3. Rush-Rage-Games

    Rush-Rage-Games

    Joined:
    Sep 9, 2010
    Posts:
    1,997
  4. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    OK, sorry, in A-Typical BigMisterB fashion, I can't leave sleeping dogs lie....

    Updates to your basic script as as follows:

    DragDrop... Added to a single object and handles all the dragging and dropping (not inventory)
    Code (csharp):
    1.  
    2. //DragDrop.js
    3. class Item{
    4.     var texture : Texture2D;
    5.     var name : String;
    6.     var gameObject : GameObject;
    7.     var prefab : GameObject;
    8. }
    9.  
    10. static var item : Item;
    11. static var toolSelected : boolean = false;
    12. private var mouseDown : boolean = false;
    13. private var rightdown=0.0;
    14.  
    15. function CaptureMouse(){
    16.     if(Input.GetMouseButtonDown(0))
    17.         mouseDown = true;
    18.    
    19.     if(Input.GetMouseButtonUp(0)  mouseDown){
    20.         mouseDown = false;
    21.         toolSelected=false;
    22.     }
    23. }
    24.  
    25. function Update(){
    26.     CaptureMouse();
    27. }
    28.  
    29. function OnGUI(){
    30.     if(toolSelected  mouseDown){
    31.         GUI.depth = 10;
    32.         var mousePos : Vector3 = Input.mousePosition;
    33.         var pos : Rect = Rect(mousePos.x  - item.texture.width / 2
    34.             ,Screen.height - mousePos.y - item.texture.height / 2,
    35.             item.texture.width, item.texture.height);
    36.         GUI.Label(pos,item.texture);
    37.     }
    38. }
    39.  
    AddToInventory... This is to be placed on any object you want added to the inventory click and drag, or right click on it.
    Code (csharp):
    1.  
    2. //AddToInventory.js
    3. var item : Item;
    4.  
    5. var mouseDown : boolean = false;
    6. var mouseOver : boolean = false;
    7. var color : Color = Color(0.8, 0.8, 0.8,1);
    8. var rightdown=0.0;
    9.  
    10. function Start(){
    11.     item.name=this.name;
    12.     item.gameObject=gameObject;
    13. }
    14.  
    15. function OnMouseOver(){
    16.     color=Color.white;
    17.     mouseOver=true;
    18. }
    19.  
    20. function OnMouseExit(){
    21.     color=new Color(0.8, 0.8, 0.8,1);
    22.     mouseOver=false;
    23. }
    24.  
    25. function CaptureMouse(){
    26.     if(Input.GetMouseButtonDown(0)  mouseOver)
    27.         mouseDown = true;
    28.    
    29.     if(Input.GetMouseButtonUp(0)  mouseDown)
    30.         mouseDown = false;
    31.    
    32.     if(!mouseOver){
    33.         rightdown=0.0;
    34.         return;
    35.     }
    36.     if(Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2)){
    37.         MouseDown();
    38.     }
    39.     if(Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(2)){
    40.         MouseUp();
    41.     }
    42. }
    43.  
    44. function MouseDown() {
    45.     if(Input.GetMouseButtonDown(0)){
    46.         DragDrop.item = this.item;
    47.         DragDrop.toolSelected=true;
    48.     }
    49.     if(Input.GetMouseButtonDown(1)){
    50.         rightdown=Time.time;
    51.     }
    52. }
    53.  
    54. function MouseUp() {
    55.     if(Input.GetMouseButtonUp(1)  Time.time - rightdown < 0.25){
    56.         var inv=GameObject.Find("Inventory");
    57.         var bag : Bag;
    58.         if(inv) bag=inv.GetComponent("Bag");
    59.         if(bag)
    60.             bag.AddItem(item);
    61.     }
    62. }
    63.  
    64. function Update(){
    65.     CaptureMouse();
    66.     renderer.material.color=color;
    67. }
    68.  
    Bag... Added for bag control (and multiple bag control) Instead of a multi dimensional array, we now use a single array and populate the number of bags depending on that.
    Code (csharp):
    1.  
    2. //Bag.js
    3. var numberOfSlots=24;
    4. var numberOfColumns=4;
    5. var textureSize=64;
    6. var showBag=true;
    7.  
    8. private var items : Item[];
    9. private var windowRect: Rect;
    10.  
    11. function Start(){
    12.     var slots : float=numberOfSlots;
    13.     var cols : float=numberOfColumns;
    14.     items=new Item[numberOfSlots];
    15.     var rows=Mathf.Ceil(slots / cols);
    16.     print(slots / cols);
    17.  
    18.     var width = textureSize * numberOfColumns + 20;
    19.     var height = textureSize * rows + 30;
    20.     windowRect = Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height);
    21. }
    22.  
    23. function Update(){
    24.     if(Input.GetKeyDown("b")) showBag=!showBag;
    25. }
    26.  
    27. function OnGUI(){
    28.     if(showBag){
    29.         GUI.depth = 0;
    30.         CreateWindow();
    31.     }
    32. }
    33.  
    34. function DragInventory(windowID:int){
    35.     for(var i=0; i< numberOfSlots; i++){
    36.         var y=Mathf.Floor(i / numberOfColumns);
    37.         var x=i - y * numberOfColumns;
    38.         var rect = Rect(textureSize * x + 10, textureSize * y + 20, textureSize, textureSize);
    39.         var texture : Texture2D;
    40.         if(items[i])texture = items[i].texture;
    41.         var slot = GUI.Button(rect, texture);
    42.        
    43.         if(rect.Contains(Event.current.mousePosition)){
    44.             if(items[i] == null  DragDrop.item != null  Input.GetMouseButtonUp(0)){
    45.                 items[i] = DragDrop.item;
    46.                 if(items[i].gameObject){
    47.                     Destroy(items[i].gameObject);
    48.                     items[i].gameObject=null;
    49.                 }
    50.             }
    51.                
    52.             if(Input.GetMouseButtonUp(1)  items[i]  [COLOR="red"]DragDrop.toolSelected[/COLOR]){
    53.                 var go=new GameObject.CreatePrimitive(PrimitiveType.Cube);
    54.                 go.renderer.material.mainTexture=items[i].texture;
    55.                 go.AddComponent(Rigidbody);
    56.                 go.AddComponent(AddToInventory);
    57.                 var s=go.GetComponent(AddToInventory);
    58.                 s.item=items[i];
    59.                 items[i] = null;
    60.                 [COLOR="red"]DragDrop.toolSelected=false;[/COLOR]
    61.             }
    62.            
    63.             if(slot){}
    64.         }
    65.     }
    66.     GUI.DragWindow();
    67. }
    68.  
    69. function AddItem(item : Item){
    70.     for(var i=0; i< numberOfSlots; i++){
    71.         if(!items[i]){
    72.             items[i]=item;
    73.             if(item.gameObject)Destroy(item.gameObject);
    74.             return;
    75.         }
    76.     }
    77. }
    78.  
    79. function CreateWindow()
    80. {
    81.     GUI.BeginGroup(windowRect);
    82.     windowRect = GUI.Window(0, windowRect, DragInventory, "Inventory");
    83.     GUI.EndGroup();
    84. }
    85.  
    Things that will need to be added:
    -Prefab definitions and how to use them. (right now it just creates boxes with the texture on it.
    -Inventory options (texture size, column control and such.)
    -Drag and drop from a bag (to space or to another bag)
    -Declaration of a "main" bag (for use with the "show bag key") This will differentiate between loot bags/chests and the characters main bag.
    -Item stacking
    -Item usage

    Usage:
    Create a couple of boxes with different textures. (assign the textures to the item/texture.
    Create a new empty game object and attach the DragDrop and the Bag scripts to it.
    Assign the texture size to the bag and number of slots

    Run the sim
    Right click on objects to add them to the inventory
    Drag objects from the scene to the inventory
    Right click on used inventory slots to release the object back into the scene.

    (to work on is to drag inventory items out of the bag.)
     
  5. Mirace

    Mirace

    Joined:
    Nov 29, 2010
    Posts:
    481
    Thanks for sharing this, helps me lot on my inventory. But there is one bug, after you have dragged item to the inventory and released mouse, you can add same item infinite times on next slots which are free.
     
  6. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    New bag code... dunno why it wont let me change the post
    Code (csharp):
    1.  
    2. //Bag.js
    3. var numberOfSlots=24;
    4. var numberOfColumns=4;
    5. var textureSize=64;
    6. var showBag=true;
    7.  
    8. private var items : Item[];
    9. private var windowRect: Rect;
    10.  
    11. function Start(){
    12.     var slots : float=numberOfSlots;
    13.     var cols : float=numberOfColumns;
    14.     items=new Item[numberOfSlots];
    15.     var rows=Mathf.Ceil(slots / cols);
    16.     print(slots / cols);
    17.  
    18.     var width = textureSize * numberOfColumns + 20;
    19.     var height = textureSize * rows + 30;
    20.     windowRect = Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height);
    21. }
    22.  
    23. function Update(){
    24.     if(Input.GetKeyDown("b")) showBag=!showBag;
    25. }
    26.  
    27. function OnGUI(){
    28.     if(showBag){
    29.         GUI.depth = 0;
    30.         CreateWindow();
    31.     }
    32. }
    33.  
    34. function DragInventory(windowID:int){
    35.     for(var i=0; i< numberOfSlots; i++){
    36.         var y=Mathf.Floor(i / numberOfColumns);
    37.         var x=i - y * numberOfColumns;
    38.         var rect = Rect(textureSize * x + 10, textureSize * y + 20, textureSize, textureSize);
    39.         var texture : Texture2D;
    40.         if(items[i])texture = items[i].texture;
    41.         var slot = GUI.Button(rect, texture);
    42.        
    43.         if(rect.Contains(Event.current.mousePosition)){
    44.             if(items[i] == null  DragDrop.item != null  Input.GetMouseButtonUp(0)){
    45.                 items[i] = DragDrop.item;
    46.                 if(items[i].gameObject){
    47.                     Destroy(items[i].gameObject);
    48.                     items[i].gameObject=null;
    49.                 }
    50.             }
    51.                
    52.             if(Input.GetMouseButtonUp(1)  items[i]  [COLOR="red"]DragDrop.toolSelected[/COLOR]){
    53.                 var go=new GameObject.CreatePrimitive(PrimitiveType.Cube);
    54.                 go.renderer.material.mainTexture=items[i].texture;
    55.                 go.AddComponent(Rigidbody);
    56.                 go.AddComponent(AddToInventory);
    57.                 var s=go.GetComponent(AddToInventory);
    58.                 s.item=items[i];
    59.                 items[i] = null;
    60.                 [COLOR="red"]DragDrop.toolSelected=false;[/COLOR]
    61.             }
    62.            
    63.             if(slot){}
    64.         }
    65.     }
    66.     GUI.DragWindow();
    67. }
    68.  
    69. function AddItem(item : Item){
    70.     for(var i=0; i< numberOfSlots; i++){
    71.         if(!items[i]){
    72.             items[i]=item;
    73.             if(item.gameObject)Destroy(item.gameObject);
    74.             return;
    75.         }
    76.     }
    77. }
    78.  
    79. function CreateWindow()
    80. {
    81.     GUI.BeginGroup(windowRect);
    82.     windowRect = GUI.Window(0, windowRect, DragInventory, "Inventory");
    83.     GUI.EndGroup();
    84. }
    85.  
     
  7. Mirace

    Mirace

    Joined:
    Nov 29, 2010
    Posts:
    481
    BigMisterB Thanks for update, still same bug. I have noticed that if you try to add
    Code (csharp):
    1.  
    2. if(rect.Contains(Event.current.mousePosition)){
    3. if(items[i] == null  DragDrop.item != null  Input.GetMouseButtonUp(0)){
    4. items[i] = DragDrop.item;
    5. if(items[i].gameObject){
    6. Destroy(items[i].gameObject);
    7.  [COLOR="red"]DragDrop.item = null;[/COLOR]
    8. items[i].gameObject=null;
    9.     }
    10. }
    11.  
    Bug dosent exist anymore, but you will get null refence error. Any clues?

    here is my edited code:
    Code (csharp):
    1.  
    2. //Bag.js
    3.  
    4. var numberOfSlots=24;
    5.  
    6. var numberOfColumns=4;
    7.  
    8. var textureSize=64;
    9.  
    10. var showBag=true;
    11.  
    12. var ItemDropSpot : Transform;
    13.  
    14. private var items : Item[];
    15.  
    16. private var windowRect: Rect;
    17.  
    18.  
    19.  
    20. function Start(){
    21.  
    22.     var slots : float=numberOfSlots;
    23.  
    24.     var cols : float=numberOfColumns;
    25.  
    26.     items=new Item[numberOfSlots];
    27.  
    28.     var rows=Mathf.Ceil(slots / cols);
    29.  
    30.     print(slots / cols);
    31.  
    32.  
    33.  
    34.     var width = textureSize * numberOfColumns + 20;
    35.  
    36.     var height = textureSize * rows + 30;
    37.  
    38.     windowRect = Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height);
    39.  
    40. }
    41.  
    42.  
    43.  
    44. function Update(){
    45.  
    46.     if(Input.GetKeyDown("i")) showBag=!showBag;
    47.  
    48. }
    49.  
    50.  
    51.  
    52. function OnGUI(){
    53.  
    54.     if(showBag){
    55.  
    56.         GUI.depth = 0;
    57.  
    58.         CreateWindow();
    59.  
    60.     }
    61.  
    62. }
    63.  
    64.  
    65.  
    66. function DragInventory(windowID:int){
    67.  
    68.     for(var i=0; i< numberOfSlots; i++){
    69.  
    70.         var y=Mathf.Floor(i / numberOfColumns);
    71.  
    72.         var x=i - y * numberOfColumns;
    73.  
    74.         var rect = Rect(textureSize * x + 10, textureSize * y + 20, textureSize, textureSize);
    75.  
    76.         var texture : Texture2D;
    77.  
    78.         if(items[i])texture = items[i].texture;
    79.  
    80.         var slot = GUI.Button(rect, texture);
    81.  
    82.        
    83.  
    84.         if(rect.Contains(Event.current.mousePosition)){
    85.  
    86.             if(items[i] == null  DragDrop.item != null  Input.GetMouseButtonUp(0)){
    87.  
    88.                 items[i] = DragDrop.item;
    89.  
    90.                 if(items[i].gameObject){
    91.  
    92.                     Destroy(items[i].gameObject);
    93.  
    94.                     items[i].gameObject=null;
    95.  
    96.                     DragDrop.item=null;
    97.  
    98.                 }
    99.  
    100.             }
    101.  
    102.                
    103.  
    104.             if(Input.GetMouseButtonUp(1)  items[i]){
    105.  
    106.                 var go=new GameObject.CreatePrimitive(PrimitiveType.Cube);
    107.  
    108.                 go.transform.position = ItemDropSpot.transform.position;
    109.  
    110.                 go.renderer.material.mainTexture=items[i].texture;
    111.  
    112.                 go.AddComponent(Rigidbody);
    113.  
    114.                 go.AddComponent(AddToInventory);
    115.  
    116.                 var s=go.GetComponent(AddToInventory);
    117.  
    118.                 s.item=items[i];
    119.  
    120.                 items[i] = null;
    121.  
    122.             }
    123.  
    124.            
    125.  
    126.             if(slot){}
    127.  
    128.         }
    129.  
    130.     }
    131.  
    132.     GUI.DragWindow();
    133.  
    134. }
    135.  
    136.  
    137.  
    138. function AddItem(item : Item){
    139.  
    140.     for(var i=0; i< numberOfSlots; i++){
    141.  
    142.         if(!items[i]){
    143.  
    144.             items[i]=item;
    145.  
    146.             if(item.gameObject)Destroy(item.gameObject);
    147.  
    148.             return;
    149.  
    150.         }
    151.  
    152.     }
    153.  
    154. }
    155.  
    156.  
    157.  
    158. function CreateWindow()
    159.  
    160. {
    161.  
    162.     GUI.BeginGroup(windowRect);
    163.  
    164.     windowRect = GUI.Window(0, windowRect, DragInventory, "Inventory");
    165.  
    166.     GUI.EndGroup();
    167.  
    168. }
    169.  
    I added drop spawn point
     
    Last edited: Aug 2, 2011
  8. Roseland1985

    Roseland1985

    Joined:
    Apr 13, 2012
    Posts:
    1
    How do I go about putting this into script? I'm taking a class in game production and I'm trying to input an inventory system much like is being described here, but I can't seem to be able to get the script to work, I keep getting parsing errors and various other errors...
     
  9. Tobias J.

    Tobias J.

    Joined:
    Feb 21, 2012
    Posts:
    423
    Hi RoseLand1985,

    To get some replies, I suggest you tell us exactly where/on what you have put the scripts. Copy/paste the errors you get.
     
  10. Lapius

    Lapius

    Joined:
    Mar 3, 2013
    Posts:
    11
    nice sistem here, but can anyone tell how to make dragable and dropable from bag? Cuz now i can just right click and drop, but cant move around inventory
     
  11. MentalTOAO

    MentalTOAO

    Joined:
    Nov 10, 2013
    Posts:
    3
    Since this helped me get together a working prototype of an drag&drop inventory, here's the fixed version.
    It includes fixes for the errors (as far as they are not coming from missing references on the components (e.g. Item drop spot on the Bag or texture on the AddToInventory)). Also you can now move stuff inside the inventory gui and drop it (drop spot required) on right click. Also fixed item sizes.

    DragDrop.js (drop onto any persistent empty GO in your scene, it's just a mouse click/drag manager)
    Code (csharp):
    1.  
    2. //DragDrop.js
    3.  
    4. class Item{
    5.     var texture : Texture2D;
    6.     var name : String;
    7.     var gameObject : GameObject;
    8.     var prefab : GameObject;
    9. }
    10.  
    11.  
    12.  
    13. static var item : Item = null;
    14. static var toolSelected : boolean = false;
    15. static var textureSize : int = 64;
    16. static var contained = false;
    17.  
    18. private var mouseDown : boolean = false;
    19. private var rightdown=0.0;
    20.  
    21. function CaptureMouse()
    22. {
    23.     if(Input.GetMouseButtonDown(0))
    24.         mouseDown = true;
    25.  
    26.     if(Input.GetMouseButtonUp(0)  mouseDown)
    27.     {
    28.         mouseDown = false;
    29.         toolSelected=false;
    30.     }
    31. }
    32.  
    33. function Update()
    34. {
    35.     CaptureMouse();
    36. }
    37.  
    38. function OnGUI(){
    39.  
    40.     if(item)
    41.     {
    42.         GUI.depth = -1;
    43.         var mousePos : Vector3 = Input.mousePosition;
    44.         var pos : Rect = Rect(mousePos.x  - textureSize / 2
    45.             ,Screen.height - mousePos.y - textureSize / 2,
    46.             textureSize, textureSize);
    47.         GUI.Label(pos,item.texture);
    48.     }
    49. }
    50.  
    Bag.js (drop this onto your player)
    Code (csharp):
    1. //Bag.js
    2.  
    3.  
    4.  
    5. var numberOfSlots=24;
    6. var numberOfColumns=4;
    7. var textureSize=64;
    8. var showBag=true;
    9. var ItemDropSpot : Transform;
    10. private var items : Item[];
    11. private var windowRect: Rect;
    12.  
    13. function Start(){
    14.     var slots : float=numberOfSlots;
    15.     var cols : float=numberOfColumns;
    16.     items=new Item[numberOfSlots];
    17.     var rows=Mathf.Ceil(slots / cols);
    18.     var width = textureSize * numberOfColumns + 20;
    19.     var height = textureSize * rows + 30;
    20.     windowRect = Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height);
    21. }
    22.  
    23. function Update(){
    24.     if(Input.GetKeyDown("i")) showBag=!showBag;
    25. }
    26.  
    27. function OnGUI(){
    28.     if(showBag){
    29.         GUI.depth = 0;
    30.         CreateWindow();
    31.     }
    32. }
    33.  
    34. function DragInventory(windowID:int)
    35. {
    36.     var mousePos : Vector3 = Event.current.mousePosition;
    37.     var contained = (mousePos.x > 0  mousePos.y > 0)  (windowRect.width > mousePos.x  windowRect.height > mousePos.y);
    38.    
    39.     DragDrop.contained = contained;
    40.  
    41.     for(var i=0; i< numberOfSlots; i++)
    42.     {
    43.         var y=Mathf.Floor(i / numberOfColumns);
    44.         var x=i - y * numberOfColumns;
    45.         var rect = Rect(textureSize * x + 10, textureSize * y + 20, textureSize, textureSize);
    46.         var texture : Texture2D;
    47.  
    48.         if(items[i])
    49.             texture = items[i].texture;
    50.  
    51.         var slot = GUI.Button(rect, texture);
    52.        
    53.         if(contained  rect.Contains(Event.current.mousePosition))
    54.         {
    55.             if(items[i] != null  DragDrop.item == null  Input.GetMouseButtonDown(0))
    56.             {
    57.                 DragDrop.item = items[i];
    58.                 items[i] = null;
    59.                 DragDrop.toolSelected = true;
    60.             }
    61.  
    62.             if(items[i] == null  DragDrop.item != null  Input.GetMouseButtonUp(0))
    63.             {
    64.                 items[i] = DragDrop.item;
    65.                 if(items[i].gameObject)
    66.                 {
    67.                     Destroy(items[i].gameObject);
    68.                     items[i].gameObject=null;
    69.                 }
    70.                 DragDrop.item=null;
    71.             }
    72.                
    73.             if(Input.GetMouseButtonUp(1)  items[i])
    74.             {
    75.                 var go=new GameObject.CreatePrimitive(PrimitiveType.Cube);
    76.                 go.transform.position = ItemDropSpot.transform.position;
    77.                 go.renderer.material.mainTexture=items[i].texture;
    78.                 go.AddComponent(Rigidbody);
    79.                 go.AddComponent(AddToInventory);
    80.                 var s=go.GetComponent(AddToInventory);
    81.                 s.item=items[i];
    82.                 items[i] = null;
    83.             }
    84.            
    85.             if(slot){}
    86.         }
    87.     }
    88.     GUI.DragWindow();
    89. }
    90.  
    91.     function AddItem(item : Item){
    92.         for(var i=0; i< numberOfSlots; i++){
    93.             if(!items[i]){
    94.                 items[i]=item;
    95.                 if(item.gameObject)Destroy(item.gameObject);
    96.                 return;
    97.             }
    98.         }
    99.     }
    100.  
    101.     function CreateWindow()
    102.     {
    103.         GUI.BeginGroup(windowRect);
    104.         windowRect = GUI.Window(0, windowRect, DragInventory, "Inventory");
    105.         GUI.EndGroup();
    106.     }
    107.  
    AddToInventory.js (drop this onto any object you wish to pick up via mouse click)
    Code (csharp):
    1. //AddToInventory.js
    2.  
    3. var item : Item;
    4. var mouseDown : boolean = false;
    5. var mouseOver : boolean = false;
    6. var color : Color = Color(0.8, 0.8, 0.8,1);
    7. var rightdown=0.0;
    8.  
    9. private var oldColor : Color;
    10.  
    11. function Start()
    12. {
    13.     item.name=this.name;
    14.     item.gameObject=gameObject;
    15.     oldColor = color = renderer.material.color;
    16. }
    17.  
    18.  
    19.  
    20. function OnMouseOver()
    21. {
    22.     color=Color.white;
    23.     mouseOver=true;
    24. }
    25.  
    26.  
    27.  
    28. function OnMouseExit()
    29. {
    30.     color=oldColor;
    31.     mouseOver=false;
    32. }
    33.  
    34.  
    35.  
    36. function CaptureMouse()
    37. {
    38.     if(Input.GetMouseButtonDown(0)  mouseOver)
    39.         mouseDown = true;
    40.  
    41.     if(Input.GetMouseButtonUp(0)  mouseDown)
    42.         mouseDown = false;
    43.  
    44.     if(!mouseOver)
    45.     {
    46.         rightdown=0.0;
    47.         return;
    48.     }
    49.  
    50.     if(Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2))
    51.     {
    52.         MouseDown();
    53.     }
    54.  
    55.     if(Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(2))
    56.     {
    57.         MouseUp();
    58.     }
    59. }
    60.  
    61.  
    62.  
    63. function MouseDown()
    64. {
    65.     if(Input.GetMouseButtonDown(0))
    66.     {
    67.         DragDrop.item = this.item;
    68.         DragDrop.toolSelected=true;
    69.     }
    70.  
    71.     if(Input.GetMouseButtonDown(1))
    72.     {
    73.         rightdown=Time.time;
    74.     }
    75. }
    76.  
    77.  
    78.  
    79. function MouseUp()
    80. {
    81.     if(Input.GetMouseButtonUp(1)  Time.time - rightdown < 0.25)
    82.     {
    83.         var inv=GameObject.Find("Inventory");
    84.         var bag : Bag;
    85.         if(inv) bag=inv.GetComponent("Bag");
    86.         if(bag)
    87.             bag.AddItem(item);
    88.     }
    89. }
    90.  
    91.  
    92.  
    93. function Update()
    94. {
    95.     CaptureMouse();
    96.     renderer.material.color=color;
    97. }
     
  12. ohlin

    ohlin

    Joined:
    Mar 3, 2013
    Posts:
    17
    the code is missing logic operators. and throwing errors in unity 5. im going out on a limb and assuming they are all ands. Hope this works.
     
  13. welby_dev

    welby_dev

    Joined:
    Apr 24, 2013
    Posts:
    2
    Good thread.
    I rewrote the above bits of JavaScript code in C#, (with a little help from a JavaScript to C# for Unity program, which can be found here, http://www.m2h.nl/files/js_to_c.php ).

    I made a few small adjustments so everything worked okay.

    DragDrop.cs (drop onto any persistent empty GO in your scene, it's just a mouse click/drag manager)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. // http://forum.unity3d.com/threads/here-is-a-drag-and-drop-inventory.98893/
    5.  
    6. //handles all dragging dropping in scene, just added to one gameobject
    7. public class DragDrop : MonoBehaviour {
    8.     public static Item item = null;
    9.     public static bool  toolSelected = false; //<-- I don't know what this is for.
    10.     public static int textureSize = 64;
    11.     public static bool contained = false;
    12.  
    13.     private bool  mouseDown = false;
    14.     private float rightdown = 0.0f;
    15.  
    16.     void CaptureMouse (){
    17.         if (Input.GetMouseButtonDown (0)) {
    18.             mouseDown = true;
    19.         }
    20.  
    21.         if(Input.GetMouseButtonUp(0) && mouseDown)
    22.         {
    23.             mouseDown = false;
    24.             toolSelected = false;
    25.         }
    26.     }
    27.  
    28.     void Update (){
    29.         CaptureMouse();
    30.     }
    31.  
    32.     void OnGUI (){
    33.         if(item != null)
    34.         {
    35.             GUI.depth = -1;
    36.             Vector3 mousePos = Input.mousePosition;
    37.             Rect pos = new Rect(mousePos.x  - textureSize / 2,
    38.                 Screen.height - mousePos.y - textureSize / 2,
    39.                 textureSize, textureSize);
    40.             GUI.Label(pos, item.texture);
    41.         }
    42.     }
    43. }
    Item.cs (I put the Item class in a separate file for organization.)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. //separate class for Item for file organization
    5. public class Item {
    6.     public Texture2D texture;
    7.     public string name;
    8.     public GameObject gameObject;
    9.     public GameObject prefab;
    10. }
    Bag.cs (drop this onto your 'player', Note: GameObject must be named "Inventory" in this case, so GameObject.Find can find it)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. // http://forum.unity3d.com/threads/here-is-a-drag-and-drop-inventory.98893/
    6.  
    7. //holds items picked up, (multiple bags allowed), add to player or GO w/ bag
    8. public class Bag : MonoBehaviour {
    9.     int numberOfSlots = 12;
    10.     int numberOfColumns = 3;
    11.     int textureSize = 64;
    12.     bool showBag = true;
    13.     Transform ItemDropSpot;
    14.     private Item[] items;
    15.     private Rect windowRect;
    16.  
    17.     void Start (){
    18.         float slots = numberOfSlots;
    19.         float cols = numberOfColumns;
    20.         items = new Item[numberOfSlots];
    21.         int rows = (int) Mathf.Ceil(slots / cols);
    22.         int width = textureSize * numberOfColumns + 20;
    23.         int height = textureSize * rows + 30;
    24.         windowRect = new Rect((Screen.width - width) / 2, (Screen.height - height) / 2, width, height);
    25.     }
    26.  
    27.     void Update (){
    28.         if (Input.GetKeyDown ("i")) {
    29.             showBag = !showBag;
    30.         }
    31.     }
    32.  
    33.     void OnGUI (){
    34.         if(showBag){
    35.             GUI.depth = 0;
    36.             CreateWindow();
    37.         }
    38.     }
    39.  
    40.     void DragInventory ( int windowID ){
    41.         Vector3 mousePos = Event.current.mousePosition;
    42.         bool contained = (mousePos.x > 0 && mousePos.y > 0) && (windowRect.width > mousePos.x && windowRect.height > mousePos.y);
    43.  
    44.         DragDrop.contained = contained;
    45.         bool windowDrag = true;
    46.  
    47.         for(int i = 0; i < numberOfSlots; i++)
    48.         {
    49.             int y = (int) Mathf.Floor(i / numberOfColumns);
    50.             int x = i - y * numberOfColumns;
    51.             Rect rect = new Rect(textureSize * x + 10, textureSize * y + 20, textureSize, textureSize);
    52.  
    53.             bool slot = false;
    54.             if (items [i] != null) {
    55.                 Texture2D texture;
    56.                 texture = items [i].texture;
    57.                 slot = GUI.Button(rect, texture);
    58.             }
    59.  
    60.             if(contained && rect.Contains(Event.current.mousePosition))
    61.             {
    62.                 if(items[i] != null && DragDrop.item == null && Input.GetMouseButtonDown(0))
    63.                 {
    64.                     DragDrop.item = items[i];
    65.                     items[i] = null;
    66.                     DragDrop.toolSelected = true;
    67.                 }
    68.  
    69.                 if(items[i] == null && DragDrop.item != null && Input.GetMouseButtonUp(0))
    70.                 {
    71.                     items[i] = DragDrop.item;
    72.                     if(items[i].gameObject)
    73.                     {
    74.                         Destroy(items[i].gameObject);
    75.                         items[i].gameObject=null;
    76.                     }
    77.                     DragDrop.item = null;
    78.                 }
    79.  
    80.                 //If you right click a thing in the bag.
    81.                 //In this instance, it's used for removing the thing from the slot.
    82.                 if(Input.GetMouseButtonUp(1) && items[i] != null)
    83.                 {
    84.                    
    85.                     /* //This section is a rough bit of trying to remove thing from bag, and put back into world.
    86.                     GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
    87.                     go.transform.position = ItemDropSpot.transform.position;
    88.                     go.GetComponent<Renderer>().material.mainTexture = items[i].texture;
    89.                     go.AddComponent<Rigidbody>();
    90.                     go.AddComponent<AddToInventory>();
    91.                     AddToInventory s = go.GetComponent<AddToInventory>();
    92.                     s.item = items[i];
    93.                     items[i] = null;
    94.                     */
    95.  
    96.                     //I'm gonna just delete it from the bag to keep it simple.
    97.                     items[i] = null;
    98.  
    99.                 }
    100.  
    101.                 if(slot){}
    102.             }
    103.         }
    104.         //If you wanna try to move the window around at runtime, you can try the line below.
    105.         //GUI.DragWindow();
    106.     }
    107.  
    108.     public void AddItem ( Item item ){
    109.         for(int i=0; i < numberOfSlots; i++){
    110.             if(items[i] == null){
    111.                 items[i] = item;
    112.                 if(item.gameObject){
    113.                     Destroy(item.gameObject);
    114.                 }
    115.                 return;
    116.             }
    117.         }
    118.     }
    119.  
    120.     void CreateWindow (){
    121.         GUI.BeginGroup(windowRect);
    122.         windowRect = GUI.Window(0, windowRect, DragInventory, "Inventory");
    123.         GUI.EndGroup();
    124.     }
    125. }
    AddToInventory.cs (drop this onto any object you wish to pick up via mouse click, drag w/ left, instant w/ quick right)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. // http://forum.unity3d.com/threads/here-is-a-drag-and-drop-inventory.98893/
    5.  
    6. //enables gameobject to be added to the inventory
    7. public class AddToInventory : MonoBehaviour {
    8.     public string name = "DefaultItemName";
    9.  
    10.     [HideInInspector] public Item item = new Item();
    11.     bool mouseDown = false;
    12.     bool mouseOver = false;
    13.     Color color = new Color(0.4f, 0.4f, 0.4f, 1);
    14.     float rightdown = 0.0f;
    15.  
    16.     private Color oldColor;
    17.  
    18.     void Start (){
    19.         item.name = this.name;
    20.         item.gameObject = gameObject;
    21.         item.texture = (Texture2D) GetComponent<Renderer> ().material.mainTexture;
    22.         oldColor = color;
    23.         color = GetComponent<Renderer>().material.color;
    24.         color = oldColor;
    25.     }
    26.  
    27.  
    28.     void OnMouseOver (){
    29.         color = Color.white;
    30.         mouseOver = true;
    31.     }
    32.  
    33.  
    34.     void OnMouseExit (){
    35.         color = oldColor;
    36.         mouseOver = false;
    37.     }
    38.  
    39.  
    40.     void CaptureMouse (){
    41.         if (Input.GetMouseButtonDown (0) && mouseOver) {
    42.             mouseDown = true;
    43.         }
    44.  
    45.         if (Input.GetMouseButtonUp (0) && mouseDown) {
    46.             mouseDown = false;
    47.         }
    48.  
    49.         if(!mouseOver) {
    50.             rightdown = 0.0f;
    51.             return;
    52.         }
    53.  
    54.         if(Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2)) {
    55.             MouseDown();
    56.         }
    57.  
    58.         if(Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1) || Input.GetMouseButtonUp(2)) {
    59.             MouseUp();
    60.         }
    61.     }
    62.  
    63.  
    64.     void MouseDown (){
    65.         if(Input.GetMouseButtonDown(0)) { //left click and dragging
    66.             DragDrop.item = this.item;
    67.             DragDrop.toolSelected = true;
    68.         }
    69.            
    70.         if(Input.GetMouseButtonDown(1)) { //right clicked a thing
    71.             rightdown = Time.time;
    72.         }
    73.     }
    74.  
    75.  
    76.     void MouseUp (){
    77.         if(Input.GetMouseButtonUp(1) && (Time.time - rightdown) < 0.25f)
    78.         {
    79.             GameObject inv = GameObject.Find("Inventory");
    80.             Bag bag;
    81.             if (inv) {
    82.                 bag = inv.GetComponent<Bag> ();
    83.                 if (bag) {
    84.                     bag.AddItem (item);
    85.                 }
    86.             }
    87.         }
    88.     }
    89.  
    90.  
    91.     void Update (){
    92.         CaptureMouse();
    93.         GetComponent<Renderer>().material.color = color;
    94.     }
    95. }
    Hope this helps anyone else curious about where to start on programming something like inventory.
     
  14. sngdan

    sngdan

    Joined:
    Feb 7, 2014
    Posts:
    1,154
    Search on YouTube for @BoredMormon tutorial. There was a pretty straight forward approach, it gave me an idea or two, I ended up with a slightly modified version, but this was very helpful. His is using the UI, something I did not yet make my mind up about...
     
    welby_dev and Kiwasi like this.
  15. welby_dev

    welby_dev

    Joined:
    Apr 24, 2013
    Posts:
    2
    I actually liked that @BoredMormon solution so much, that it's currently the basis of what I'm currently using for my game project.


    Here's the code if anyone wants it, but I highly recommend understanding the basics of it. (The method names make it pretty self explanatory though.)
    Watch the video to watch the setup.

    DragHandler.cs <<< Goes on the gameobject prefabs that get dragged.
    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine.EventSystems;
    3.  
    4. public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
    5.     public static GameObject itemBeingDragged;
    6.     Vector3 startPosition;
    7.     Transform startParent;
    8.  
    9.     #region IBeginDragHandler implementation
    10.  
    11.     public void OnBeginDrag (PointerEventData eventData)
    12.     {
    13.         itemBeingDragged = gameObject;
    14.         startPosition = transform.position;
    15.         startParent = transform.parent;
    16.         GetComponent<CanvasGroup>().blocksRaycasts = false;
    17.     }
    18.  
    19.     #endregion
    20.  
    21.     #region IDragHandler implementation
    22.  
    23.     public void OnDrag (PointerEventData eventData)
    24.     {
    25.         transform.position = Input.mousePosition;
    26.     }
    27.  
    28.     #endregion
    29.  
    30.     #region IEndDragHandler implementation
    31.  
    32.     public void OnEndDrag (PointerEventData eventData)
    33.     {
    34.         itemBeingDragged = null;
    35.         GetComponent<CanvasGroup>().blocksRaycasts = true;
    36.         if (transform.parent == startParent) {
    37.             transform.position = startPosition;
    38.         }
    39.     }
    40.  
    41.     #endregion
    42.  
    43.  
    44. }
    Slot.cs <<< Goes on the slots, which are panels with grid layout groups.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.EventSystems;
    4. using System.Xml.Linq;
    5.  
    6. public class Slot : MonoBehaviour, IDropHandler {
    7.     public GameObject item {
    8.         get {
    9.             if (transform.childCount > 0) {
    10.                 return transform.GetChild (0).gameObject;
    11.             }
    12.             return null;
    13.         }
    14.     }
    15.  
    16.     #region IDropHandler implementation
    17.     public void OnDrop (PointerEventData eventData)
    18.     {
    19.         if (!item) {
    20.             DragHandler.itemBeingDragged.transform.SetParent (transform);
    21.  
    22.             ExecuteEvents.ExecuteHierarchy<IHasChanged> (gameObject, null, (x, y) => x.HasChanged ());
    23.         } else {
    24.             item.transform.SetParent (DragHandler.itemBeingDragged.transform.parent);
    25.             DragHandler.itemBeingDragged.transform.SetParent (transform);
    26.  
    27.             ExecuteEvents.ExecuteHierarchy<IHasChanged> (gameObject, null, (x, y) => x.HasChanged ());
    28.         }
    29.     }
    30.     #endregion
    31. }
    32.  
    Inventory.cs <<< Goes on Canvas, and is passed the panel with the slots to read and the text box.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.EventSystems;
    4. using UnityEngine.UI;
    5.  
    6. public class Inventory : MonoBehaviour, IHasChanged {
    7.     [SerializeField] Transform slots;
    8.     [SerializeField] Text inventoryText;
    9.  
    10.     void Start() {
    11.         HasChanged ();
    12.     }
    13.  
    14.     #region IHasChanged implementation
    15.  
    16.     public void HasChanged ()
    17.     {
    18.         //blah blah blah, This updates every time this thing gets called
    19.         System.Text.StringBuilder builder = new System.Text.StringBuilder();
    20.         builder.Append (" - ");
    21.         foreach (Transform slotTransform in slots) {
    22.             GameObject item = slotTransform.GetComponent<Slot> ().item;
    23.             if (item) {
    24.                 builder.Append (item.name);
    25.                 builder.Append (" - ");
    26.             }
    27.         }
    28.         inventoryText.text = builder.ToString ();
    29.     }
    30.  
    31.     #endregion
    32. }
    33.  
    34.  
    35. namespace UnityEngine.EventSystems {
    36.     public interface IHasChanged : IEventSystemHandler {
    37.         void HasChanged();
    38.     }
    39. }
     
    Orbitallion and RogueDeus like this.