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?

3
  • Use modulo % operator, i%length then the rerun value always within boundary. So you no need of 40 such assignments Commented Jun 8, 2017 at 4: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.. Commented Jun 8, 2017 at 4:20
  • you can search for the cell and set the value to that, Commented Jun 8, 2017 at 4:37

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
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- stackoverflow.com/q/44474684/4282366 . Thanks
0

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

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

        txtRef.text = Value.ToString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.