Dennis Liu
Dennis Liu

Reputation: 303

How To Make Multi Array in Unity c#?

How to convert the variable below to become Multi Array Variable ?

The code example :

public GameObject Mayonnaise;
    Text Qty;
    Text Price;
    Text Have;

    public GameObject Cheese;
    Text Qty;
    Text Price;
    Text Have;

    public GameObject Flour;
    Text Qty;
    Text Price;
    Text Have;

    public GameObject Sugar;
    Text Qty;
    Text Price;
    Text Have;

I want that gameobject Mayonnaise contain Qty, Price, Have;

So it will look like : Mayonnaise["qty","Price","Have"]

So I no need to create too many variable name with the same one.

How is it in Unity C# ?

Thanks

Upvotes: 0

Views: 229

Answers (1)

Programmer
Programmer

Reputation: 125255

I want that gameobject Mayonnaise contain Qty, Price, Have;

A game Object cannot contain those. It looks like you are looking for a way to hold those those variables and using scripts to do this is appropriate.

So I no need to create too many variable name with the same one

All you need is a script that holds each food type. You can then create arrays of each food type. This is what this question sounds to me and hopefully, I read this correctly.

If you look very close in your question, you will see that Qty,Price, and Have variables appeared in all scripts. This is where inheritance should be used.

Food class:

public class Food
{
    protected Text Qty;
    protected Text Price;
    protected Text Have;

    public void setQty(Text Qty)
    {
        this.Qty = Qty;
    }

    public void setPrice(Text Price)
    {
        this.Price = Price;
    }

    public void setHave(Text Have)
    {
        this.Have = Have;
    }

    public Text getQty()
    {
        return this.Qty;
    }

    public Text getPrice()
    {
        return this.Price;
    }

    public Text getHave()
    {
        return this.Have;
    }
}

You can then Create your Mayonnaise,Cheese,Flour and Sugar classes and inherit from Food on all of them.

public class Mayonnaise : Food
{

}

public class Cheese : Food
{

}

public class Flour : Food
{

}

public class Sugar : Food
{

}

Now, to answer your question about creating multiple arrays of them, below is like what you are looking for.

const int Size = 4;

Mayonnaise[] mayonnaise;
Cheese[] cheese;
Flour[] flour;
Sugar[] sugar;

void Start()
{
    mayonnaise = new Mayonnaise[Size];
    cheese = new Cheese[Size];
    flour = new Flour[Size];
    sugar = new Sugar[Size];

    //Create instance of of them
    for (int i = 0; i < Size; i++)
    {
        mayonnaise[i] = new Mayonnaise();
        cheese[i] = new Cheese();
        flour[i] = new Flour();
        sugar[i] = new Sugar();
    }

    mayonnaise[0].setHave(SomeTextComponent);
    mayonnaise[0].getHave().text = "Some Text";
    string text = mayonnaise[0].getHave().text;
}

Upvotes: 2

Related Questions