Quick question, probably fairly easy, but not getting results on google/unity forum.
I have a custom class, which is straight forward:
// This works!
public class TestData
{
public string ID;
public Vector3 position;
public Vector3 rotation;
}
public class Test : MonoBehaviour
{
public List<TestData> testData = new List<TestData>();
}
I’m using the class TestData very much as a list, and every time In my scripts I have to write:
public List<TestData> {NAME} = new List<TestData>();
I’m wondering if it’s possible to automatically define the TestData class as a list?
For example something like this:
public class TestData
{
public string ID;
public Vector3 position;
public Vector3 rotation;
}
// Is this possible?
public class TestDataList
{
public List<TestData>(); // Define automatically as list?
}
public class Test: MonoBehaviour
{
public TestDataList testData = new TestDataList(); // So i can skip the List<TestData> at every declaration?
}
In theory yes, by making TestDataList inherit from List like so:
public class TestDataList : List<TestData>
{
}
BUT
There is a problem where the Unity serialization engine and inspector won’t treat this object as a list. Which sucks.
In the end though I don’t see the difference between saying “TestDataList” and “List”. They’re nearly the same number of chars (2 extra with the < >).
You could also just use an array if you don’t expect to resize it in code:
public class Test : MonoBehaviour
{
public TestData[] testData;
}
Also note that your example with the List as a member TestDataList will actually work:
public class TestDataList
{
public List<TestData> lst = new List<TestData>(); //needs to be defined as a member
}
The only problem is that it’ll be in a nested object. Which will look weird in the inspector, and you’ll need to access it as ‘testData.lst’, or whatever you named it.
Lastly, when you say:
I want to clarify… you’re not using TestData as a list. You’re using TestData in a list. TestData is still a single object, you just generally use TestData as a member of a list because you expect multiple TestData instances.
Maybe if you defined a use case for why you’d want to do this. Just because you think it’s less typing? Intellisense helps you fill in pretty much all code. As soon as you type new and hit space, it gives you a solution that you can select to fill in the rest of it.
I’m honestly trying to think of when I might use something like that. So I’m just curious.
Yes i tried that aswell, but in the end declaring public List<TestData> {NAME} = new List<TestData>(); makes more sense to me than writing public TestDataList {NAME}; and accessing testData.lst!