- Home /
How do I access a variables created in a function with another function?
I have created a multiple arrays in a function that I would like to accress from another function. For instance I have created a function called getStuff and in it I create several arrays and will them with objects or strings or some numeric varibles. Point is a few different types of arrays. Once the function is complete I want to keep the arrays around until I press a button then I want the arrays to be destroyed and new arrays made with new variables to fill them. Any ideas or question?
In C# all variables that are declared inside of a function are marked for garbage collection when that function call ends. When you declare a class variable, it is accessible within that class. Your best bet is to access these variables and set their content inside of functions. C++ allows for static function member variables that can be useful for monitoring how many times a function has been called, but this is not possible in C#.
int var;
int var = 0; //initializes the variable to 0
private int var; //same as int var
protected int var; //can be accessed by itself and child classes
public int var; //can be accessed by any class in the project
Answer by Lovrenc · Jan 11, 2013 at 08:55 PM
If you do this:
void myFunct() {
int myVar = 5;
}
You CAN NOT ACCESS that myVar ANYWHERE outside that function. You could however do this:
In your class, declare needed variables:
int myVar;
float[] myArray;
In your function you use those variables to save the data you need.
void DoSomething() {
//DO CALCULATIONS
myVar = 5;
myArray = new float[]{1f, .5f, .1f};
}
Then when you press a button you just call the DoSomething
function. It will create new values by itself and store them in those variables.
Thanks, I actualy just copy the arrays I made in the functions into some global arrays. So that is pretty much what you showed. Thanks again
Your answer
Follow this Question
Related Questions
Array Element number 1 Answer
Find gameObject with higher variable 1 Answer
Variable value doesn't change 1 Answer
changing variables values !! 1 Answer