I have a small problem with my script. I declare an int variable testInt, then create a List and add the testInt variable to it. This should create a reference, right? However, when I change the value of the variable inside the list, it only changes that variable’s value, and not the original testInt
What am I doing wrong?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Test : MonoBehaviour {
public int testInt = 1;
void Start() {
TestFunction();
}
void TestFunction() {
List<int> testList = new List<int>();
testList.Add(testInt);
for(int i = 0; i < testList.Count; i++) {
testList *++;*
Why should it? An int is not a reference type, but a value type. It is copied into the list when you add it. If you want the class field to change, you’ll have to encapsulate it in a reference type and add that reference to the list.
For example:
public class ValueWrapper<T>
{
public ValueWrapper(T value)
{
Value = value;
}
public T Value;
}
public class TestReferenceList : MonoBehaviour
{
public ValueWrapper<int> TestInt = new ValueWrapper<int>(1);
public List<ValueWrapper<int>> TestList;
void Start()
{
TestFunc();
}
void TestFunc()
{
TestList = new List<ValueWrapper<int>>();
TestList.Add(TestInt);
for (int i = 0; i < TestList.Count; i++)
{
TestList*.Value++;*
_ Debug.Log("Class field: " + TestInt.Value + ", list element: " + TestList*.Value);_
_ // prints Class field: 2, list element: 2*_ * }* * }* * }* EDIT: it’s also doable with reflection, where you add the [FieldInfo][1] to the list, but that’s usually not cost-effective.
_*[1]: Microsoft Learn: Build skills that open doors in your career