L
L
Lesh482020-12-23 15:56:24
C++ / C#
Lesh48, 2020-12-23 15:56:24

When a variable is passed to a function, it changes. How to make sure this doesn't happen?

When a variable is passed to a function, it changes. Here is the code:

void Start()
{
  int[] pos = new int[2];
  pos[0] = 1;
  pos[1] = 2;

  ChangePos(pos);

  Debug.Log(pos[0] + " " + pos[1]); // вывод 3 4

}

void ChangePos(int[] value_to_change)
{
  value_to_change[0] = 3;
  value_to_change[1] = 4;
}

How to make sure that when passing the value of a variable to a function and changing it in the function, its value does not change?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Korotenko, 2020-12-23
@Lesh48

Something like this. Why did you need to change?

void ChangePos(int[] value_to_change)
        {
            var nn = new int[value_to_change.Length];
            value_to_change.CopyTo(nn,0);
            nn[0] = 3;
            nn[1] = 4;
        }

V
Vasily Bannikov, 2020-12-23
@vabka


How to make sure that when passing the value of a variable to a function and changing it in the function, its value does not change?

Do not change the value, for example)
In your case, you can pass a copy of the original array to the method or create a copy of the array inside ChangePos itself, as suggested by Vladimir Korotenko .
But if ChangePos will not change the values ​​in the passed array, then what is its meaning?
PS: put Unity aside for later and learn C#

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question