Is there any way to pass a default value to list-elements? I mean when I edit a list in edit mode and add an element, it should initialize its value to a custom default value, not 0.
_
[System.Serializeable]
public class Test {
int value = 500;
}
public class TestManager : MonoBehaviour {
public Test testInt;
public List<Test> testInts;
}
_
In the inspector, testInt.value has 500 as I wanted. But what if I want to have multiple Test Instances? Therefore I will use the list. But if I increase the size of the list,** it will have their values set to 0, not 500**.
_
I have tried to implement a constructor that should force them to serialize:
[System.Serializeable]
public class Test {
int value = 500;
public Test(){
Debug.Log("Iam called but the following line not?");
value = 500;
}
}
and this will be called whereever I add one Test-Instance to the list as the console shows the debug.Log. However it still does not initialize the value to 500. I dont know why, I mean this is such a simple task and it only works on single fields, not with lists.
Ok I found a solution in case somebody has the same problem.
No need of cTor or ISerializableCallbackReceiver. This uses the Reset Callback (from the coq) that will also call at instanciation. Cheers!
_
[System.Serializeable]
public class Test {
int value = 500;
}
public class TestManager : MonoBehaviour {
public Test testInt;
public List<Test> testInts;
void Reset(){
testInts = new List<Test>(){
new Test()
};
}
}
For anyone looking for answer now:
I ended up creating a button in my scriptable object that when clicked assigned values to its field automatically so that I don’t have to manually.
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Item Database", menuName = "Create database/Item Database")]
public class ItemDatabase : ScriptableObject
{
public List<Item> itemList;
public bool Valid => itemList != null ? itemList.Count > 0 : false;
public Item FetchItemByID(int id)
{
for (int i = 0; i < itemList.Count; i++)
{
if (itemList*.itemId == id)*
return itemList*;* } return null; }
public void AssignIds() { foreach(Item item in itemList) { item.itemId = itemList.IndexOf(item); } } }
[System.Serializable] public class Item { public int itemId; public string itemName; public string itemDescription; public string slug; public bool stackable; public string itemType; public GameObject itemPrefab; public Sprite itemIcon;
public Item() { this.itemId = -1; } } ---------- using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine;
[CustomEditor(typeof(ItemDatabase))] public class ItemDatabaseEditor : Editor { public override void OnInspectorGUI() { base.OnInspectorGUI(); var script = (ItemDatabase)target;