How can I add ints to a list then change the values of the original ints?

Let’s I declare “public int ExampleIntA, ExampleIntB, ExampleIntC,” etc., then I do the following function at Start:

    public void FillIntList ()
    {
        IntList.Add(ExampleIntA);
        IntList.Add(ExampleIntB);
        IntList.Add(ExampleIntC);
         for (int i = 0; i < IntList.Count; i++)
            IntList *= i;*

}
…After that function is run, I want ExampleIntA, ExampleIntB and ExampleIntC (the ones that I declared at the top) to be numbered sequentially, not just the ints inside the list. What would be the best way to do that? It seems to me that when you add a GameObject to a list, it’s actually putting the original object inside the list, but when you add an int to a list, it just makes a copy of the int’s current value and moves on.

int also knows as Int32 is a struct, not a class. In c# structkeyword is used to define a value type, while the class keyword is used to define a reference type. That’s why you are changing the value and can’t change the reference.
For example, if you have to change X position of cached GameObject, you can’t just change its position.X, because Vector3 is a struct and it won’t change in reference GameObject. Instead of this you should create new Vector3 with new X value and set this vector to position of cached GameObject.


You should create your own class that holds this int value:

using System.Collections.Generic;
using UnityEngine;

public class TestReference : MonoBehaviour
{

	MyInt ExampleIntA;
	MyInt ExampleIntB;
	MyInt ExampleIntC;
    List<MyInt> IntList;
	private void Start() {
		ExampleIntA	= new MyInt(56);
		ExampleIntB = new MyInt(99);
		ExampleIntC = new MyInt(47);
            IntList = new List<MyInt>();
		FillIntList();
	}

	public class MyInt {
		public MyInt(int MyIntValue) => this.MyIntValue = MyIntValue;
		public int MyIntValue { get; set; }
		public override string ToString() => MyIntValue.ToString();
	}

	public void FillIntList() {
		IntList.Add(ExampleIntA);
		IntList.Add(ExampleIntB);
		IntList.Add(ExampleIntC);
		foreach (var i in IntList) Debug.Log(i); 
		for (int i = 0; i < IntList.Count; i++)
			IntList*.MyIntValue = i;*
  •  Debug.Log(ExampleIntA + " " + ExampleIntB + " " + ExampleIntC);*
    
  • }*
    }