Home > other >  In C# can I use a List key as a argument in a method?
In C# can I use a List key as a argument in a method?

Time:06-26

Hey everyone first time Asker here.

so i'm writing a method in C# to let me equip a item or level it up if acquired. Doesn't sound hard right? hahaha yea.... i'm succumbing to the madness at this point and am fairly confident i'm lost my sanity in code.

My current code for the scriptable objects has each item having 2 things a itemclass and a itemLevel.

so whiplevel1 would have itemClass whip and itemLevel 1.

And if i already had whiplevel1 and was running this again id expect either other weapons or whiplevel 2 but never whiplevel1 again.

I have made many iterations of this code over and over trying to get this to work.

this is a small example

{
    public ItemDatabase items;
    private static Database instance;
    private static int Whip = 0;

    private void Awake()
    {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);

        }
        else
        {
            Destroy(gameObject);
        }
    }


    public static Item GetChooseableItemByItemLevel(string itemClass,int itemLevel)
    {
        for(int i = 0; i >= instance.items.allItems.Count; i  )
        {
            if (instance.items.allItems[i].itemLevel == itemLevel && instance.items.allItems[i].itemClass == itemClass)
            {
                
                Database.itemClass  = 1;
                return instance.items.allItems[i];
                
            }
            
        }
        return null;
    }```

if using Database.itemClass worked id be golden and could do the rest but i dont know how to do that in C#

CodePudding user response:

It seems you are trying to access a property itemClass that doesn't exist on your Database class. You do access an itemClass property in your if statement though.

Perhaps replacing

Database.itemClass  = 1;

with

instance.items.allItems[i].itemClass  = 1;

would help?

Then you are actually using your current instance of the Database class, and able to access the items ItemDatabase from it.

The way you tried to do it using Database.itemClass would only work if you had itemClass statically defined in the Database class. You need an actual instance of the Database class to access your ItemDatabase. (See Microsoft's documentation on static classes here)

CodePudding user response:

for(int i = 0; i >= instance.items.allItems.Count; i  )

This is the problem, that loop will only execute (infinitely) if you have 0 items on list, should be probably:

for(int i = 0; i < instance.items.allItems.Count; i  )
  • Related