[英]How To Make Multi Array in Unity c#?
如何將下面的變量轉換為多數組變量?
代碼示例:
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;
我希望游戲對象蛋黃醬包含數量,價格,價格;
這樣看起來像:Mayonnaise [“ qty”,“ Price”,“ Have”]
因此,我無需使用相同的變量創建太多的變量名。
在Unity C#中效果如何?
謝謝
我希望游戲對象蛋黃醬包含數量,價格,價格;
游戲對象不能包含這些對象。 您似乎正在尋找一種方法來保存這些變量,並使用腳本來執行此操作是適當的。
所以我不需要用相同的名字創建太多的變量名
您所需要的只是一個保存每種食物類型的腳本。 然后,您可以創建每種食物類型的數組。 這就是我所想的問題,希望我能正確閱讀。
如果您的問題看起來很接近,您會看到Qty
, Price
和Have
變量出現在所有腳本中。 這是應該使用inheritance
地方。
Food
類:
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;
}
}
然后,您可以創建您的Mayonnaise
, Cheese
, Flour
和Sugar
並從Food
繼承它們。
public class Mayonnaise : Food
{
}
public class Cheese : Food
{
}
public class Flour : Food
{
}
public class Sugar : Food
{
}
現在,要回答有關創建多個數組的問題,下面的內容與您想要的一樣。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.