AZSWQ
AZSWQ

Reputation: 319

c# assign values from a for loop to individual variables

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?

Upvotes: 0

Views: 3217

Answers (2)

Ben Brookes
Ben Brookes

Reputation: 439

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();
}

Upvotes: 1

AZSWQ
AZSWQ

Reputation: 319

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

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

        txtRef.text = Value.ToString();

Upvotes: 0

Related Questions