Setting two int equal each other, is causing a different behaviour, than two int arrays equalling each other
Hello, I'm not sure if this is a Bug, or if there are other reasons for this problem but assinging an int[] (Script2) to equal another int[] (Script 1) is causing both variables to be connected, so by changing the value of second int[](Script 2) is automatically updating the first int[] (Script 1) . By doing exactly the same with two normal int the behaviour is a completly different one. By Updating the int of Script 2, the int of Script 1 is staying unchanged.
So how can the behaviour of the same action end up being so different?
Script 1
using UnityEngine;
using System.Collections;
public class Script1 : MonoBehaviour {
public static Script1 Script1Singleton;
public int TestInteger =0;
public int[] TestIntegerArray ={0};
// Use this for initialization
void Awake () {
Script1Singleton =this;
}
}
Script 2
using UnityEngine;
using System.Collections;
public class Script2 : MonoBehaviour {
public int TestInteger =0;
public int[] TestIntegerArray ={0};
// Use this for initialization
void Start () {
TestInteger = Script1.Script1Singleton.TestInteger;
TestIntegerArray = Script1.Script1Singleton.TestIntegerArray;
}
// Update is called once per frame
void Update () {
TestInteger++;
TestIntegerArray[0]++;
print("Script1 Int: "+Script1.Script1Singleton.TestInteger+ " Script2 Int:"+TestInteger);
print("Script1 Int[]: "+Script1.Script1Singleton.TestIntegerArray[0]+ " Script2 Int[]:"+TestIntegerArray[0]);
}
}
Console Log
Answer by hexagonius · Oct 24, 2016 at 07:52 PM
welcome to the world of programming, introducing value type vs reference type. While an integer is a value type, directly inheriting it's value,a reference type inherits the address to it's value. int a = 1.
int b = a // b and are 1.
b++ // a stays 1, b is 2.
int[] a = {1}
int[] b = a // b now "points" to a's array.
b[0]++ // a[0] and b[0] both read 1, because they point to the same value.
this means, assigning one array variable to the other copies the address to the actual array. from now on indexing into it works the same from both variables
Oh that's why, thanks for the quick answer. You helped me a lot!