Search Unity

C# // References to different Array Elements

Discussion in 'Scripting' started by Quatum1000, Nov 24, 2017.

  1. Quatum1000

    Quatum1000

    Joined:
    Oct 5, 2014
    Posts:
    889
    Hi everyone,

    eg I like to have 3 arrays for example A[], B[] C[]. Now I like to have references in C[] to elements of A[] and elements of B[].

    C[0] = reference to A[2]
    C[1] = reference to A[0]
    C[2] = reference to B[0]
    C[3] = reference to B[1]
    C[4] = reference to B[4]

    C[] should contain references and no data copy.
    If I change C[3] = 99 it should change B[1] to 99 as well.

    Does anyone have some lines of example code to solve this in unity?
    Thank you.
     
    Last edited: Nov 24, 2017
  2. Grizmu

    Grizmu

    Joined:
    Aug 27, 2013
    Posts:
    131
    A possible solution to that is to write your own wrapper:
    Code (CSharp):
    1. public class RefValue<T> {
    2.     public T value;
    3.  
    4.     public RefValue(T value) {
    5.         this.value = value;
    6.     }
    7.  
    8.     public override string ToString() {
    9.         return value.ToString();
    10.     }
    11. }
    12.  
    13. public class Testt : MonoBehaviour {
    14.  
    15.     RefValue<int>[] A = new RefValue<int>[5];
    16.     RefValue<int>[] B = new RefValue<int>[5];
    17.     RefValue<int>[] C = new RefValue<int>[5];
    18.  
    19.     public void OnEnable() {
    20.         for(int i = 0; i < 5; i++) {
    21.             A[i] = new RefValue<int>(i);
    22.             B[i] = new RefValue<int>(i + 5);
    23.         }
    24.  
    25.         C[0] = A[2];
    26.         C[1] = A[0];
    27.         C[2] = B[0];
    28.         C[3] = B[1];
    29.         C[4] = B[4];
    30.  
    31.         string str="";
    32.  
    33.         Debug.Log("Before modifying references:");
    34.         for(int i = 0; i < 5; i++) {
    35.  
    36.             str += string.Format("A[{0}]= {1}, ", i, A[i]);
    37.             str += string.Format("B[{0}]= {1}"  , i, B[i]);
    38.             str += System.Environment.NewLine;
    39.         }
    40.         Debug.Log(str);
    41.  
    42.         for(int i = 0; i < 5; i++) {
    43.             C[i].value = 99;
    44.         }
    45.  
    46.         Debug.Log("After modifying references:");
    47.         str = "";
    48.         for(int i = 0; i < 5; i++) {
    49.             str += string.Format("A[{0}]= {1}, ", i, A[i]);
    50.             str += string.Format("B[{0}]= {1}", i, B[i]);
    51.             str += System.Environment.NewLine;
    52.         }
    53.         Debug.Log(str);
    54.     }
    55. }
     
    Quatum1000 likes this.
  3. Quatum1000

    Quatum1000

    Joined:
    Oct 5, 2014
    Posts:
    889
    Thank you!
     
    Grizmu likes this.