I’m trying to create a function where if I pass an int variable to it, it changes it’s value. I tried the following but it just changes “var” inside the function but doesn’t change the value of “variable1” and “variable2”. Is there any way to do this?
int variable1;
int variable2;
void Function(int var) {
var = 1;
}
void Start() {
Function(variable1);
Function(variable2);
}
How could I create a function that actually changes the value of “variable1” and “variable2” to 1 without creating multiple functions that contain the name of these variables?
Because var is just declared inside that function. You can do something like this though:
int Function(int var){
var =1;
return var;
}
Meaning you will return the value of what you set it to, so you can do something like variable1 = Function(variable1);
Here are 3 ways you could do what you’re trying to achieve.
Note that you probably shouldnt use keywords like that when defining variables ‘var’ etc. Consider at a glance you might not know what it is right away, perhaps consider naming it ‘num’ instead.
// 1) 'ref'
// ref keyword means "pass by reference" - edits
// made in this function affect the actual variable
int someNum = 5;
AddOne(ref someNum);
// someNum now = 6
void AddOne(ref int i)
{
i++;
}
// 2) 'return'
// As stated you could return the value instead
int someNum = 5;
// Call AddOne, passing in our someNum value and set the value
// that AddOne returns back into out someNum variable.
someNum = AddOne(someNum);
int AddOne(int i)
{
// You could return right away by doing something like
// return ++i;
// however for verbosity, im not in this example.
i += 1;
return i;
}
// 3) 'Extension method'
int someNum = 5;
// I cant think of how to correctly say what an extension method
// actually is so heres a link:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
// https://www.dotnetperls.com/extension
someNum.AddOne();
public static int AddOne(this int i)
{
i += 1;
return i;
}