c#将for循环中的值赋给各个变量

时间:2017-06-08 04:05:52

标签: c# for-loop unity3d

我在for循环中有Cell和Value的值。例如,当i = 0时,value将是“第一个值”,我想将其分配给A0Text.text。当i = 1时,值将是“第二个值”,我想分配给A1Text.text .. -

for (int i = 0; i < BLOCKS.Count; i++)
{
//possible values of Cell are A0, A1, A2 ...
var Cell = currentBLOCKData["cell"];

var Value = currentBLOCKData["value"];

....

然后我有与Cell

同名的字段
//possible cellName are - A0Text, A1text, A2Text .....
string cellName = Cell + "Text";

我想分配

A0Text.text = First value in above field - Value
A1Text.text = 2nd value in above field - Value
A2Text.text = 3rd value in above field - Value

我如何制作上述作品?

2 个答案:

答案 0 :(得分:1)

Gameobject.Find可能会很慢,我觉得效率很低。在哪里可以避免使用它,尽量做到。为什么不为Text组件创建公共数组,在检查器中分配它们,然后在循环中遍历数组。

public Text[] textArray; //assign in inspector

for(int i = 0; i < BLOCKS.Count; i++){
    //.. your other code here
    textArray[i].text = Value.ToString();
}

答案 1 :(得分:0)

是的 - 我想通了 - 搜索和分配如下:

        txtRef = GameObject.Find(cellName).GetComponent<Text>();

        txtRef.text = Value.ToString();
相关问题