- Home /
Calling for two variables in a list
What would be the best way to get 2 variables from a list item. I have an inventory system where one item has multiple variables , and the two I am trying to access are ItemName which is a string and then IsEqquipped which is a bool . So far everything I have done has only needed to call on one variable at a time from the item in the list .Now save what inventory the player has equipped i need to call two variables at once from the item.
If you are using JS use hash table http://docs.unity3d.com/Documentation/ScriptReference/Hashtable.html
If you are using c# use dictionary
If your data becomes more complex you may want to look at creating a Class or Struct.
I have a custom class for the items.Right now I am just using a simple method of getting all the items in the players inventory by name and serializing it. but ive come to the point where i need to save if items in the players inventory are equipped or not and save that bool with the corresponding item. Heres some of the code i have so far
Item Class : using UnityEngine; using System.Collections;
[System.Serializable]
public class Items :ScriptableObject{
public int cost = 0;
public string ItemName = "";
public string ItemType = "";
public string description = "";
public Texture2D Icon;
public GameObject ItemPrefab;
public int Id = 0 ;
public bool IsEquipped = false ;
Saving player inventory through serialize when items are added from the market :
private void Serialize <T>(List<Items> list)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
TextWriter tw = new StreamWriter("PlayerInv.txt");
serializer.Serialize(tw, list);
tw.Close();
public void PurchaseCon ( int windowID){
if (GUI.Button(new Rect(Screen.width*ButtonPlacementX3,Screen.height*ButtonPlacementY3,Screen.width*ButtonWidth2,Screen.height*ButtonHeight2),"Confirn"))
{
for(int i = 0; i < cart.Count;i++)
{
GameObject findplayer = GameObject.FindWithTag("Player");
pl = findplayer.GetComponent<PlayerInventory>();
pl.playerinv.Add(cart[i]);
pl.playerinvname.Add(cart[i].ItemName);
cart.Clear();
purchasecon = false;
List<Items> playerlist = pl.playerinvname;
Serialize<string>(playerlist);
}
}
Answer by Sundar · Dec 23, 2013 at 03:05 PM
Here you go
using System;
using System.Collections.Generic;
// here string is the "name" of the item and bool is "Is equipped"
Dictionary<string, bool> items = new Dictionary<string, bool>();
// add items
items.add( "item1", true );// item1 is equipped
items.add( "item2", false )// item2 is not equipped
// find item equipped or not
if( items.ContainsKey("item1"))// check dictionary has "item1"
{
bool isEquipped = items["item1"];
if(isEquipped)Debug.Log("item1 is equipped");
else Debug.Log("item1 is not equipped");
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Count object list duplicates 1 Answer
Inventory System wont work 2 Answers
C# Lists & Inventory Logic 0 Answers