0
\$\begingroup\$

I have this code to add 10 point if someone click the button and change the question. But it returns 10 point every time. I want to make it 10,20,30,40... etc.

IEnumerator TransitionToNextQuestion() {

            unAnsweredQuestions.Remove(currentQuestion);
            yield return new WaitForSeconds (timeBetweenQuestions);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }

        public void addPoint(int addPoint) {
            point = point + addPoint;
        }

        public void ButtonDown() {
            addPoint (10);
            Debug.Log (point);
            StartCoroutine (TransitionToNextQuestion());

        }
\$\endgroup\$
0
\$\begingroup\$

That is because ints are value types, this means they are located in the stack, which, on the other hand, classes are reference types, so they are located in dynamic memory. In a nutshell: when you have a class, you have its memory's reference, when you have a value type, you have its value, but not its memory reference.

When you pass a value type as a parameter and you modify it inside a function, it will not be modified, you could use a ref or out modifier in your parameter instead, with that, you also pass the location in memory of that value type. Or you could do a wrapper class.

Example:

public class Example : MonoBehaviour
{
    int integer;

    void Start()
    {
        AddTen(ref integer);
        Debug.Log(integer);  /// Will return 10.
    }

    void AddTen(ref int _value)
    {
        _value += 10;
    }
}

So, in short, if you want to modify a value type (structs, string, int, char, double, float, etc.) you should use the ref or out modifiers.

Check in more depth the differences between value and reference types. Hope it helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.