0

I have the value of Cell and Value in a for loop. For example when i=0, value will be "first value" which I want to assign to A0Text.text. When i=1, , value will be "second value" which I want to assign to 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"];

....

Then I have fields named with the same name as Cell

//possible cellName are - A0Text, A1text, A2Text .....
string cellName = Cell + "Text";

I want to assign

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

How can I make the above assigments?

AZSWQ
  • 199
  • 5
  • 24
  • Use modulo % operator, i%length then the rerun value always within boundary. So you no need of 40 such assignments – Ankireddy Polu Jun 08 '17 at 04:16
  • Can you please elaborate your answer? So for example when i=0, value will be "first value" which I want to assign to A0Text.text. When i=1, , value will be "second value" which I want to assign to A1Text.text.. – AZSWQ Jun 08 '17 at 04:20
  • you can search for the cell and set the value to that, – Vicky S Jun 08 '17 at 04:37

2 Answers2

1

Gameobject.Find can be quite slow and I'd consider it pretty inefficient. Where you can avoid using it, try your best to. Why not create a public array for your Text components, assign them in the inspector and then iterate through your array in your loop.

public Text[] textArray; //assign in inspector

for(int i = 0; i < BLOCKS.Count; i++){
    //.. your other code here
    textArray[i].text = Value.ToString();
}
Ben Brookes
  • 419
  • 4
  • 15
  • Thanks - Sounded good but then does the script needs to be assigned to each text label ? In that case that might be less efficient than GameObject.Find ? Also I get an out of range array exception. – AZSWQ Jun 08 '17 at 21:19
  • The other way around: Each text label needs to be assigned to the script. Can you show me your code? Do you need help avoiding that exception? – Ben Brookes Jun 09 '17 at 07:25
  • I had to take a step back because when i tested on android, i cant even read the json file because i use Application.Datapath. Can you help with that question- https://stackoverflow.com/q/44474684/4282366 . Thanks – AZSWQ Jun 10 '17 at 15:32
0

Yes - I figured it out - Searching and assigning as below:

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

        txtRef.text = Value.ToString();
AZSWQ
  • 199
  • 5
  • 24