Ngui Backpack System

Source: Internet
Author: User

The backpack system, as its name implies, is a system that stores the various items required by the player's character as a schoolbag. Let me just say this: a backpack system has a lot of inventory, an inventory to store an item. The backpack system has 16 inventory items. We need to implement a simple function: whenever a certain time to generate an item, put the item in the backpack system interface. Further, if the items present in the backpack and the items to be placed are the same, only change the quantity of the item; If there is no upcoming item in the backpack, add the item in the backpack, place it in the empty position, and put it in a random place. As shown, the bottom right corner of each inventory is the number of items.

Now, when I write this article, I'm not quite clear about the logic. When I finish writing, not only I, you crossing believe also will not feel confused. Our backpack system is comprised of 16 cells, cell 1~16. The bottom support of the backpack system, in fact, thanks to the Ngui Uidragdropitem script, through the class name we can understand that this is the drag function of a script, we need to do is to inherit the class, rewrite an event handler function Ondragdroprelease ( Gameobject surface), this function is the main function: when we drag the item down (Release), this function will be triggered. But

(1) Dragged items must add a script that inherits from the Uidragdropitem script class.

(2) The dragged object must add a collision body, and the Ngui interaction must add a collision body.

(3) The UI object to be placed must also have a collision body, for the same reason.

So, cell1~cell16 these 16 UI game objects must be added on the collision body. They all have the same function and are all subject to the drag and drop of the item. When the functions of multiple game objects are the same, U3d tells us that it is best to save them as prefab, so the cell presets are created.

And the function of the item we can naturally think of, is to be able to implement drag-and-drop function, and be able to receive the drag release after the event, to make some event processing. We also save the item as a preset, knapsackitem the preset body. The Ondragdroprelease (Gameobject surface) function is the implementation detail ... Place the item in the center of the inventory, and when an item is placed in another inventory containing other items, the items are swapped, and the item's subscript (quantity) changes in real time when items in the inventory are added. There is a feature I added myself, feeling useless, is to drag an item into another inventory containing the same items, two items merged, the item subscript ( quantity ) increased.

A hierarchical view of the backpack system and the contents of the corresponding scene view.

The preset contains such a script, KnapsackItem.cs. This script can be implemented to put items into the backpack, and when the target object dragged into the other items, the two items are swapped. At this point, we implement the ability to put items in one inventory into other inventory.

The above is just a function of the backpack system, the items already in the backpack to replace the inventory, or Exchange two inventory items. We should also add a feature: Add Items. Here, we can't add items as we do in a specific game, so we use a single button per press, and the inventory will have a random extra item (test method).

Let's think about the script that adds items to which game object should be placed?

Adding items should be items in the inventory, so this function should contain a method for the script that hangs on the game object that symbolizes the inventory. As soon as we call this method, items are added in the inventory according to certain rules. Script name We define the Knapsack.cs script, which defines a method for the public type: PickUp (). We think slowly, a little bit of expansion. First of all, the simplest idea is that we forget to add an item to the backpack system with each X key, we think the CELL1 has the highest priority. Every time the function is executed, it should be traversed from cell1 to Cell16, and when the inventory is empty, we forget to add an item to the inventory, and the function of adding the item is Ngui provided to us, Nguitools.addchild ( Itemparent.gameobject, item); I feel that the function should be to create an item using Gameobject's instantiate function, And the item as the first parameter itemparent.gameobject the child object of the game object, that's all. We have to remember to change the sprite of the item and break out of the loop to make sure this is our one-time add item, and if there is no break, all empty inventory will be filled with item, which is not the result we want to see.

So far, our backpack system is not feeling very sore, because many of the same items are placed in different inventory. The result we want is to store the same items in each inventory, and the items need to be labeled in quantity.

Let's take a look at our implementation of the more egg-aching backpack system.

Complaining about this, let's think about how we can improve. Before adding item to the inventory, we have to determine if there are items in the inventory that are the same as the items that will be added, and if so, increase the value of the item directly, and save the unnecessary overhead of adding items. One trick is to add an identity variable, bool Hasthesame, to the pickup function, which starts with false and, once the same item is in the inventory, performs an operation that increases the number of items, and Hasthesame becomes true. It would be nice to put the code added to the empty inventory that we just implemented into the IF (!hasthesame) {}. Below I attach Knapsack.cs and KnapsackItem.cs script, let everybody look, there are shortcomings please correct me.

1 usingUnityengine;2 usingSystem.Collections;3 4  Public classKnapsack:monobehaviour {5      Publicgameobject Item;6      Public string[] itemnames;7     //Use this for initialization8     voidStart () {9     Ten     } One      A     //Update is called once per frame -     voidUpdate () { -         if(Input.getkeydown (keycode.x)) the         { - PickUp (); -         } -     } +     /// <summary> -     ///This function will get an item +     ///loop through each cell, and if the item you want to add already exists in the inventory, you only need to increase the number of items that exist in the inventory. A     ///if the item to be added does not exist, add the item at     ///determine which of the above conditions is in a flag position -     /// </summary> -      Public voidPickUp () -     { -         BOOLHasthesame =false; -         intindex = Random.range (0,3); in  -         //for (int i = 0; i < Transform.childcount; i++) to         //{ +         //    //itemparent indicates the window where items are to be placed -         //Transform itemparent = Transform. Getchild (i); the  *         //    //if the item you want to add already exists in the inventory, you only need to increase the number of items that exist in the inventory. $         //if (Itemparent.childcount > 0)Panax Notoginseng         //    { -         //        //print (Itemparent.getcomponent<uisprite> (). spritename); the         //        //print (Itemparent.getcomponentinchildren<uisprite> (). spritename); +         //if (itemparent.getchild (0). Getcomponent<uisprite> (). Spritename = = Itemnames[index]) A         //        {                    the         //            //itemparent.getcomponentinchildren<knapsackitem> (). Addcount (1); +         //itemparent.getchild (0). Getcomponent<knapsackitem> (). Addcount (1); -         //Hasthesame = true; $         //Break ; $         //        } -         //    } -         //} the         //If the inventory does not have the same items -         if(!hasthesame)Wuyi         { the              for(inti =0; i < Transform.childcount; i++) -             { Wu                 //itemparent indicates the window where items are to be placed -Transform itemparent =transform. Getchild (i); About  $                 if(Itemparent.childcount = =0) -                 { -                     //adds a sub-object to a game object that is a preset body prefab -Gameobject go =nguitools.addchild (Itemparent.gameobject, item); AGo. Getcomponent<uisprite> (). Spritename =Itemnames[index]; +Go.transform.localPosition =Vector3.zero; the  -                      Break; $                 } the             } the         } the          the     } -}

1 usingUnityengine;2 usingSystem.Collections;3 4 //using the Inherit Uidragdropitem class5  Public classKnapsackitem:uidragdropitem6 {7 8      Publicuisprite Selfsprite;9      PublicUILabel Numberlabel;Ten     intCount =1; One  A      Public voidAddcount (intvalue) -     { -Count + =value; theNumberlabel.text =count. ToString (); -     } -  -     protected Override voidondragdroprelease (gameobject surface) +     { -         Base. Ondragdroprelease (surface); +         //if the dragged target object has no sub-objects, it becomes the child object of the target object directly, and is zeroed in the target object's coordinate system . A         if(Surface.tag = ="Cell") at         { -Transform.parent =Surface.transform; -Transform.localposition =Vector3.zero; -             //if the target object being dragged is a child of the cell, because the depth of the child object is large, above, and there are collider components -             //Two items should be exchanged at this time item -}Else if(Surface.tag = ="Item"){ in             //Merge two identical items -             if(Transform. Getcomponent<uisprite> (). Spritename = = surface. Getcomponent<uisprite>(). Spritename) to             { +Transform.parent = Surface.transform.parent.transform;//Surface represents items -Transform.localposition =Vector3.zero; the Destroy (surface); *Addcount (1); $             }Panax Notoginseng             Else -             { theTransform newparent = surface.transform.parent;//The old and new father is relative to the dragged item.  +Transform oldparent =transform.parent; ASurface.transform.parent =oldparent; theSurface.transform.localPosition =Vector3.zero; +Transform.parent =newparent; -Transform.localposition =Vector3.zero; $             }            $         }        -     } -}
View Code

Finally, summarize the essentials of the backpack system:

(1) Items that need to be dragged need to be added to the script class that inherits from UIDragDropItem.cs, and the ondragdroprelease () function needs to be rewritten. What you need to do is: when the inventory is empty, items are dragged into the center of the inventory, items are already in the inventory, and items are added at the same time as items that need to be dragged, items are already in the inventory, and two items are exchanged when the items that need to be dragged are not the same.

(2) Object and inventory objects must be added to the collision body components to achieve the drag function.

(3) In addition, a script class is needed to realize the function of object dynamic increase. It is also considered from the point of view that the inventory is empty and not empty. In the end is from scratch or directly to the existing items to increase the quantity, see you crossing ability.

         

Ngui Backpack System

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.