Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by mrgohut · May 10, 2014 at 03:37 PM · arraylistinventory

Convert Inventory from JS to C# (problem with list)

Hello :) I'm converting now Inventory system but i'm stuck on List / Arrays (JS). Here's my script:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 [AddComponentMenu ("Inventory/Character Sheet")]
 [RequireComponent(typeof (Inventory))]
 public class Character : MonoBehaviour {
 
     //The Character window (CSheet).
     public Transform WeaponSlot; //This is where the Weapons are going to go (be parented too). In my case it's the "Melee" gameobject.
     
     //private Item[] ArmorSlot;
     private List<Item> ArmorSlot; //This is the built in Array that stores the Items equipped. You can change this to static if you want to access it from another script.
     //public string[] ArmorSlotName; 
     public List<string> ArmorSlotName; //This determines how many slots the character has (Head, Legs, Weapon and so on) and the text on each slot.
     //public Rect[] buttonPositions; 
     public List<Rect> buttonPositions; //This list will contain where all buttons, equipped or not will be and SHOULD HAVE THE SAME NUMBER OF cells as the ArmorSlot array.
     
     Vector2 windowSize = new Vector2(375,300); //The size of the character window.
     public bool useCustomPosition = false; //Do we want to use the customPosition variable to define where on the screen the Character window will appear.
     Vector2 customPosition = new Vector2 (70, 70); //The custom position of the Character window.
     public GUISkin cSheetSkin; //This is where you can add a custom GUI skin or use the one included (CSheetSkin) under the Resources folder.
     public bool canBeDragged = true; //Can the Character window be dragged?
     
     public KeyCode onOffButton = KeyCode.I; //The key to toggle the Character window on and of.
     
     bool DebugMode = false; //If this is enabled, debug.logs will print out information when something happens (equipping items etc.).
     
     static bool csheet = false; //Helps with turning the CharacterSheet on and off.
     
     private Rect windowRect = new Rect(100,100,200,300); //Keeping track of our character window.
     
     //These are keeping track of components such as equipmentEffects and Audio.
     private Inventory playersinv; //Refers to the Inventory script.
     private bool equipmentEffectIs = false;
     private InvAudio invAudio;
     private bool invDispKeyIsSame = false;
             
     //Assign the differnet components to variables and other "behind the scenes" stuff.
     void Awake ()
     {
         playersinv = GetComponent<Inventory>();
         
         if (useCustomPosition == false)
         {
             windowRect = new Rect(Screen.width-windowSize.x-70,Screen.height-windowSize.y-(162.5f+70*2),windowSize.x,windowSize.y);
         }
         else
         {
             windowRect = new Rect(customPosition.x,customPosition.y,windowSize.x,windowSize.y);
         }
         invAudio = GetComponent<InvAudio>();
         if (GetComponent<InventoryDisplay>().onOffButton == onOffButton)
         {
             invDispKeyIsSame = true;
         }
     }
     
     //Take care of the array lengths.
     void Start ()
     {
         ArmorSlot = new Item[ArmorSlotName.Count];
         if (buttonPositions.Count != ArmorSlotName.Count)
         {
             Debug.LogError("The variables on the Character script attached to " + transform.name + " are not set up correctly. There needs to be an equal amount of slots on 'ArmorSlotName' and 'buttonPositions'.");
         }
     }
     
     //Checking if we already have somthing equipped
     bool CheckSlot(int tocheck)
     {
         bool toreturn = false;
         if(ArmorSlot[tocheck]!=null){
             toreturn=true;
         }
         return toreturn;
     }
     
     //Using the item. If we assign a slot, we already know where to equip it.
     public void UseItem(Item i, int slot, bool autoequip)
     {
         if(i.isEquipment){
             //This is in case we dbl click the item, it will auto equip it. REMEMBER TO MAKE THE ITEM TYPE AND THE SLOT YOU WANT IT TO BE EQUIPPED TO HAVE THE SAME NAME.
             if(autoequip)
             {
                 int index = 0; //Keeping track of where we are in the list.
                 int equipto = 0; //Keeping track of where we want to be.
                 foreach(string a in ArmorSlotName) //Loop through all the named slots on the armorslots list
                 {
                     if(a == i.itemType) //if the name is the same as the armor type.
                     {
                         equipto=index; //We aim for that slot.
                     }
                     index++; //We move on to the next slot.
                 }
                 EquipItem(i,equipto);
             }
             else //If we dont auto equip it then it means we must of tried to equip it to a slot so we make sure the item can be equipped to that slot.
             {
                 if(i.itemType==ArmorSlotName[slot]) //If types match.
                 {
                     EquipItem(i,slot); //Equip the item to the slot.
                 }
             }
         }
         if (DebugMode)
         {
             Debug.Log(i.name + " has been used");
         }
     }
     
     //Equip an item to a slot.
     void EquipItem(Item i, int slot)
     {
         if(i.itemType == ArmorSlotName[slot]) //If the item can be equipped there:
         {
             if(CheckSlot(slot)) //If theres an item equipped to that slot we unequip it first:
             {
                 UnequipItem(ArmorSlot[slot]);
                 ArmorSlot[slot]=null;
             }
             ArmorSlot[slot]=i; //When we find the slot we set it to the item.
             
             gameObject.SendMessage ("PlayEquipSound", SendMessageOptions.DontRequireReceiver); //Play sound
             
             //We tell the Item to handle EquipmentEffects (if any).
             if (i.GetComponent<EquipmentEffect>() != null)
             {
                 equipmentEffectIs = true;
                 i.GetComponent<EquipmentEffect>().EquipmentEffectToggle(equipmentEffectIs);
             }
             
             //If the item is also a weapon we call the PlaceWeapon function.
             if (i.isAlsoWeapon == true)
             {
                 if (i.equippedWeaponVersion != null)
                 {
                     PlaceWeapon(i);
                 }
                 
                 else 
                 {
                     Debug.LogError("Remember to assign the equip weapon variable!");
                 }
             }
             if (DebugMode)
             {
                 Debug.Log(i.name + " has been equipped");
             }
             
             playersinv.RemoveItem(i.transform); //We remove the item from the inventory
         }
     }
     
     //Unequip an item.
     void UnequipItem(Item i)
     {
         gameObject.SendMessage ("PlayPickUpSound", SendMessageOptions.DontRequireReceiver); //Play sound
         
         //We tell the Item to disable EquipmentEffects (if any).
         if (i.equipmentEffect != null)
         {
             equipmentEffectIs = false;
             i.GetComponent<EquipmentEffect>().EquipmentEffectToggle(equipmentEffectIs);
         }
         
         //If it's a weapon we call the RemoveWeapon function.
         if (i.itemType == "Weapon")
         {
             RemoveWeapon(i);
         }
         if (DebugMode)
         {
             Debug.Log(i.name + " has been unequipped");
         }
         playersinv.AddItem(i.transform);
     }
     
     //Places the weapon in the hand of the Player.
     void PlaceWeapon (Item item)
     {
         GameObject Clone = GameObject.Instantiate(item.equippedWeaponVersion, WeaponSlot.position, WeaponSlot.rotation) as GameObject;
         Clone.name = item.equippedWeaponVersion.name;
         Clone.transform.parent = WeaponSlot;
         if (DebugMode)
         {
             Debug.Log(item.name + " has been placed as weapon");
         }
     }
     
     //Removes the weapon from the hand of the Player.
     void RemoveWeapon (Item item)
     {    if (item.equippedWeaponVersion != null)
         {
             Destroy(WeaponSlot.FindChild("" + item.equippedWeaponVersion.name).gameObject);
             if (DebugMode)
             {
                 Debug.Log(item.name + " has been removed as weapon");
             }
         }
     }
     
     void Update ()
     {
         //This will turn the character sheet on and off.
         if (Input.GetKeyDown(onOffButton))
         {
             if (csheet)
             {
                 csheet = false;
                 if (invDispKeyIsSame != true)
                 {
                     gameObject.SendMessage ("ChangedState", false, SendMessageOptions.DontRequireReceiver); //Play sound
                     gameObject.SendMessage("PauseGame", false, SendMessageOptions.DontRequireReceiver); //StopPauseGame/EnableMouse/ShowMouse
                 }
             }
             else
             {
                 csheet = true;
                 if (invDispKeyIsSame != true)
                 {
                     gameObject.SendMessage ("ChangedState", true, SendMessageOptions.DontRequireReceiver); //Play sound
                     gameObject.SendMessage("PauseGame", true, SendMessageOptions.DontRequireReceiver); //PauseGame/DisableMouse/HideMouse
                 }
             }
         }
     }
     
     //Draw the Character Window
     void OnGUI()
     {
         GUI.skin = cSheetSkin; //Use the cSheetSkin variable.
         
         if(csheet) //If the csheet is opened up.
         {
             //Make a window that shows what's in the csheet called "Character" and update the position and size variables from the window variables.
             windowRect = GUI.Window (1, windowRect, DisplayCSheetWindow, "Character");
         }
     }
     
     //This will display the character sheet and handle the buttons.
     void DisplayCSheetWindow(int windowID)
     {
         if (canBeDragged == true)
         {
             GUI.DragWindow (new Rect (0,0, 10000, 30));  //The window is dragable.
         }
         
         int index = 0;
         foreach(Item a in ArmorSlot) //Loop through the ArmorSlot array.
         {
             if(a == null)
             {
                 if(GUI.Button(buttonPositions[index], ArmorSlotName[index])) //If we click this button (that has no item equipped):
                 {
                     InventoryDisplay id = GetComponent<InventoryDisplay>();
                     if(id.itemBeingDragged != null) //If we are dragging an item:
                     {
                         EquipItem(id.itemBeingDragged,index); //Equip the Item.
                         id.ClearDraggedItem();//Stop dragging the item.
                     }
                 }
             }
             else
             {
                 if(GUI.Button(buttonPositions[index],ArmorSlot[index].itemIcon)) //If we click this button (that has an item equipped):
                 {
                     InventoryDisplay id2 = GetComponent<InventoryDisplay>();
                     if(id2.itemBeingDragged != null) //If we are dragging an item:
                     {
                         EquipItem(id2.itemBeingDragged,index); //Equip the Item.
                         id2.ClearDraggedItem(); //Stop dragging the item.
                     }
                     else if (playersinv.Contents.Count < playersinv.MaxContent) //If there is room in the inventory:
                     {
                         UnequipItem(ArmorSlot[index]); //Unequip the Item.
                         ArmorSlot[index] = null; //Clear the slot.
                         id2.ClearDraggedItem(); //Stop dragging the Item.
                     }
                     else if (DebugMode)
                     {
                         Debug.Log("Could not unequip " + ArmorSlot[index].name + " since the inventory is full");
                     }
                 }
             }
             index++;
         }
     }
 
 }


And I have this error:

Assets/Inventory/Scripts/Character.cs(62,17): error CS0029: Cannot implicitly convert type Item[]' to System.Collections.Generic.List'

in JS version there were arrays but in c# i convert it to Lists and i have couple of errors ;D Can someone help me with this ? ;/

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by robertbu · May 10, 2014 at 03:56 PM

Seems to be that the right solution is to go back to using an array for ArmorSlot. The code that uses ArmorSlot expects a fixed size array. You can hack the solution if you really want to use a List. Change line 62 to:

 ArmorSlot = new List<Item>(new Item[ArmorSlotName.Count]);

But doing it this way gives you zero benefit and some minor cost by using a List rather than a built-in array.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mrgohut · May 10, 2014 at 09:10 PM 0
Share
 ArgumentOutOfRangeException: Argument is out of range.
 

now i have this when i want to Equip my weapon. It's this lane:

 if(i.itemType == ArmorSlotName[slot]) //If the item can be equipped there:
avatar image robertbu · May 11, 2014 at 01:54 AM 0
Share

There's no initialization code for 'ArmorSlotName'. Based on the code, my guess is that 'ArmorSlotName' should be initialized in the inspector. That is, in the Inspector you would set the size and enter the strings for each entry. If so, you need to go back to an array for this variable.

Are you sure you want to go to the List class for all these arrays? You are not getting any benefit that I can see.

avatar image
0

Answer by TheDarkVoid · May 10, 2014 at 09:06 PM

Lists in c# are declared like this:

 public List<int> intList = new List<int>();
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mrgohut · May 10, 2014 at 09:15 PM 0
Share

Yes, i know, and what ?

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How can I store game data outside of scripts.(e.g Total list of inventory items) 2 Answers

A node in a childnode? 1 Answer

Setting generic list length 2 Answers

Referencing a struct/class From Another Script 3 Answers

Store multiple types of data in an Array? 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges