Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# new object(data) always creates empty objects

I’m fairly new to c# and I’m trying to create a custom object, but they always seem to be empty.

public class Item
{
    public string itemName {get;set;}
    public int itemAmount {get;set;}
    public Item (string name, int amount)
    {
        name = itemName;
        amount = itemAmount;
    }
}

public class Backpack : MonoBehaviour
{    
    void Start()
    {
       Item gold = new Item ("gold", 5)
    }
}

When I try to get gold parameters I get null, 0. Should it work like that? I wanted to use it to quickly add items to a list, and right now I would have to change all of them manually with something like
gold.itemName = "gold"; gold.itemAmount = 5.
Can I do it in another way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your assignment in the constructor is the wrong way around, instead it should be:

public Item (string name, int amount)
{
    itemName = name;
    itemAmount = amount;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading