0

I'm having a problem figuring out how to display my object's stats that are not equal to 0. Basically I have an Item class that contains 50+ variables like strength, agility, intelligence, etc... all defaulted to equal 0. Every time I click a button, it generates an object and gives some of the object's attributes non-zero values (aka strength is now 3, agility is now 2, everything else stays 0).

In my GUI script, upon clicking the generated item I wanted it to display the item's details. I just want it to display the object's attributes if they were not 0. That way I don't have 50+ lines of attributes on the item saying it's just of value 0.

A snippet of the item's details is below(Note it compiles and runs fine):

public void LootDetailWindow(int id)
{
    GUI.Label(new Rect(10, 15, 150, 80), "<color=white><size=15>" + item.Name + "</size></color>");
    GUI.Label(new Rect (10, 50, 100, 100), item.Icon);
    GUI.Label (new Rect (150, 50, 200, 100), "Level Requirement: " + item.Reqlvl.ToString() + "\nSell Value: " + item.Value);

    //here I want to create a label that for every value that is not 0, to display it.
}

So how would I go about going through each attribute and checking to see if it's 0? Thanks in advance.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user2562568
  • 367
  • 1
  • 6
  • 16

3 Answers3

2

I largely agree with the above but also consider.. you have a class with 50+ int fields, most are 0 blah blah at least consider that that class might be better of being replaced by a dictionary if you're going to tend to be enumerating its fields, or are likely to add new attributes reguarly, ie

enum attributeTypes
{
    strength,
    agility,
    ...
}

and replace your hardcoded fields with a

Dictionary<attributeTypes, int>

since you want them to default to 0 this will probably work nicely

might not be a good idea of course depending on context but could be...

tolanj
  • 3,651
  • 16
  • 30
2
foreach (PropertyInfo prop in obj.GetType().GetProperties(
    BindingFlags.Public | BindingFlags.Instance))
{
    if (prop.PropertyType != typeof(int)) continue;

    int val = (int)prop.GetValue(obj);
    if(val != 0) Console.WriteLine("{0}={1}", prop.Name, val);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You can make a custom attribute, decorate the members you're interested in with that attribute, then use reflection to iterate over the members that have your custom attribute.

Reflection is relatively slow, so remember to cache the list of conforming members after the first time.

When you have your list of members, you can get their names and actual values for your current object and perform your presentation logic.

Community
  • 1
  • 1
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104