Home > Net >  C# Making 2 variables equal one another
C# Making 2 variables equal one another

Time:05-31

I made this code which should make it so that the variables current and levelclicks equal one another. However when I run the code that is not the case.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Threading;
using System.Threading.Tasks;


public class GameManager : MonoBehaviour
{

    
    public int current;
    public int levelclicks;




    public void IncreaseValue()
    {
        levelclicks = levelclicks   1;

    }

    void LevelUp()
    {
        levelclicks = current;

    }
}

I'm pretty sure that there's nothing wrong with the code, but if there is then please tell me.

CodePudding user response:

Why it doesn't work

current and levelclicks are two int, which is a value type (a struct). That means than each of those fields have an independant value.

So what levelclicks = current; does is copy the value of current into levelclicks. And what levelclicks = levelclicks 1; does is increase the value of levelclicks. It doesn't change the value of current.

Why it wouldn't work even if it was a reference type

Even if you used a reference type (a class), that still wouldn't work, but for another reason.

levelclicks = current; would indeed make both fields reference the same object, and if you modify this object through one reference, even accessing it through the other reference would give you the modified object.

BUT with levelclicks = levelclicks 1; you would get the object referenced by levelclicks, create another object with the 1, and save a reference to this new object in levelclicks. Then levelclicks and current would not reference the same object anymore.

However, if you could modify the object in memory instead of creating a new object, it would work. But then, you wouldn't have to save the reference (since the reference didn't change). It would just be something like levelclicks.Add(1); and that method would be return void.

Back to what you want to do.

Why do you want two different variables with the same value? If you have a good reason, beneath levelclicks = levelclicks 1;, you could add

  • current = current 1;
  • current = levelclicks;
  • Related