Skip to content

Instantly share code, notes, and snippets.

@inertiave
Created August 16, 2019 07:07
Show Gist options
  • Save inertiave/babab0f21e9ec24418c1c6a4ac33e208 to your computer and use it in GitHub Desktop.
Save inertiave/babab0f21e9ec24418c1c6a4ac33e208 to your computer and use it in GitHub Desktop.
Add difference between List and Array
using System.Collections.Generic;
using UnityEngine;
public class StructOwner : MonoBehaviour {
public MyStruct myStruct;
public MyStruct myStruct2;
public NestedClass nestedClass;
public List<MyStruct> list;
public MyStruct[] array;
void Awake()
{
myStruct.stringValue = "origin";
myStruct2.stringValue = "origin";
list = new List<MyStruct>();
list.Add(new MyStruct("one"));
list.Add(new MyStruct("two"));
// index가 temp value에 접근하므로 원본 데이터 수정 불가
// List 사용시 인자가 구조체면, 더미 값이므로 set 못함
//list[1].stringValue = "aa";
Debug.Log(list[1].stringValue);
array = new MyStruct[2];
array[0]= new MyStruct("one");
array[1]= new MyStruct("two");
array[1].stringValue = "aa";
ChangeAndPrint(myStruct);
ChangeAndPrint(ref myStruct2);
// result
// copy - s:copy String, myStruct:origin
// ref - s:ref String, myStruct:ref String
}
void ChangeAndPrint(MyStruct s)
{
s.stringValue = "copy String";
Debug.Log($"copy - s:{s.stringValue}, myStruct:{myStruct.stringValue}");
}
void ChangeAndPrint(ref MyStruct s)
{
s.stringValue = "ref String";
Debug.Log($"ref - s:{s.stringValue}, myStruct:{myStruct2.stringValue}");
}
[System.Serializable]
public class NestedClass {
public string internalString;
}
}
[System.Serializable]
public struct MyStruct {
public string stringValue;
public MyStruct(string initValue)
{
stringValue = initValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment