- Home /
constructor doesn't work in C# native class
I'm trying to save data in my c# native object(not inherit from Mono) that has a list, but the list cannot be built by the constructer.
The data class:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class TestData
{
public List<string> list = new List<string>(4);
public TestData(int size)
{
Debug.Log(size);
list = new List<string>(size);
Debug.Log(list.Count);
}
}
The MonoBehavior class that build this data in start:
using UnityEngine;
using UnityEditor.Events;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Testing : MonoBehaviour
{
TestData data;
void Start()
{
data = new TestData(4);
}
}
The console always output 4 0
And I can't figure why! I'm using Unity 5.1.1.f1
Answer by Thomas-Mountainborn · Sep 24, 2015 at 05:58 PM
The output is exactly correct. list.Count outputs the amount of elements in the list - you didn't put anything in there, so it's 0.
A List does not need to be initialized with the number of elements it is supposed to hold. It is an array that expands as the amount of elements in it increases.
Thank you very much! The problem is solved. And you gave me a good lesson on not falling into what I think it should work but to check how it really works.