- Home /
type function not returning. c#
I think this is a simple question.. and i feel pretty dumb asking it TBH. but none the less, my Debug log , keeps writing "2", even though i clicked on A. (check the code :-) )
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public int testINT = 2;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Debug.Log(testINT);
if(Input.GetKey(KeyCode.A)){
calculator(testINT);
}
}
public int calculator(int x){
x = 4;
return x;
}
}
Answer by ffxz7ff · Jan 25, 2014 at 12:34 AM
The calculator function returns an x, but the value is never used. You probably want to store it in testINT, so replace
calculator(testINT);
with
testINT = calculator(testINT);
and you might get the result that you want. Also, in that case your parameter for the calculator function is unneccessary. The parameter x only lives within the function. If you want to get a value out, use the return value as stated above.
Answer by poncho · Jan 25, 2014 at 12:43 AM
When you are sending your debug, your testINT's value is 2, then IF you press the A key, you enter the calculator method, the scope of this method is that makes a copy of the info it receives, parameter x is equals to 2, then it changes its value to 4, and returns a 4
BUT, after leaving the method, the 4 you returned, is not assigned to anything, so the value 4 stays in the air, and after the line calculator(testINT); passes, it disappears, if you want to assign your value returned in calculator,
you have 2 options,
A. you reference the value, public int calculator(ref int x), with this, any change to your parameter made inside the method calculator, will be passed outside the method,
B. you change to testINT=calculator(testINT), to assign the value returned from calculator to the testINT variable. Good Luck and Happy Coding
so if i just add "ref" to the parameters, it will change the value of the assigned variable to the x?
yes but you would need to change you call to the method, from calculator(testINT); to calculator(ref testINT);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# Function that returns instantiated object 1 Answer
Get enum value out of function c# 2 Answers
Return a custom class from function 1 Answer