Trying to access a variable within for

Hello, first of all, I want to say I have no background in coding but I am trying to learn it myself through many sources.

My question is how to access the “i” value generated by the for loop within my script and use it in another script. (the “var longitude” value)

Ultimately I am trying to get plot a set of points (x,z) based on a csv file that I have.

Here’s the code that I have so far:

var csvFile : TextAsset;

function Start(){
	Longitude();
}

function Longitude () {
	/* split the contents of the file into an array of pieces separated by commas
	*/
	
	var stringArrayLongitude = csvFile.text.Split(","[0]);
	var stringArrayLatitude = csvFile.text.Split(","[0]);
	var stringArrayMembers = csvFile.text.Split(","[0]); 
	
	
	for(var i = 6; i < stringArrayLongitude.length; i+=4){
	
		var longitude = stringArrayLongitude*;*
  • }*

  • for(var j = 5; j < stringArrayLatitude.length; j+=4){*

  •  //print("The latitude is " + stringArrayLatitude[j]);*
    
  • }*

  • for(var p = 7; p < stringArrayMembers.length; p+=4){*

  •  //print("Number of members is " + stringArrayMembers[p]);*
    
  • }*

}

2 Answers

2

In this case, ‘i’ is created within the for and only has scope (only exists) within that for statement. For this to be accessible outside you would need to extend the scope by declaring the variable outside the loop, within the function or within the base of the class itself.

Alternatively, make a new variable in the class and make it equal to i within your for loop.

Thank you for the answer...I've been trying to do what you suggested but I am pretty sure I am not doing it right, is there any way you could show me an example please?

Declare a variable(e.g private int myvar), then in the for loop assign myvar to i(myvar = i;). Hope that helps.

You will find that the for loop must complete before you can use the value in the rest of the script, unless you perform the operation from within the for loop. You can use GetComponent to push the value to another script but the for loop executes so fast that the loop will be complete before the Update can use the previous value.

That is very informative meat, thanks for that input!

No Problem :)

What I do is above start make write

public int count = 1;

the for your for loop

for(count = 1, count < 10; count++){

}

then you can control your count from the inspector