Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by Noxury · Feb 11, 2018 at 05:59 PM · listserializationvaluedefault

Default value on List vanished

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.

I hope you understand what I mean.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Noxury · Feb 11, 2018 at 08:08 PM

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()
         };
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image sleepandpancakes · Feb 11, 2018 at 08:16 PM 0
Share

Thanks for this. What happens if you ins$$anonymous$$d do value = 500; in OnAfterDeserialize() without a firstCall bool check?

avatar image Noxury sleepandpancakes · Feb 11, 2018 at 08:25 PM 0
Share

I switched out the functions because otherwise OnBeforeSerialize() will mostly be called even when you dont edit anymore which is resource conso$$anonymous$$g.

The bool makes sure it will be called on the first time unity serialized this property, so this acts like a default value for single class fields like Test testInt above. If you leave the bool out, it will be resetted back to 500 everytime you want to reassign the value in the inspector.

avatar image PizzaPie · Feb 11, 2018 at 09:39 PM 0
Share

That hardly solves anything, in case of object (class) field you can just use the default value declaration on class fields as you do above, as for lists this will fail (try to hit play and stop it). Regarding to this behaviour you maximize your chances to end up with bugs, data loss, on the long run and the benefits of it hardly overcome the cons.

Cheers!

avatar image
0

Answer by jinincarnate · Mar 19, 2020 at 04:17 PM

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[i].itemId == id)
                     return itemList[i];
             }
             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;
 
         if(script.Valid)
         {
             if(GUILayout.Button("Automatic Assign Ids", GUILayout.Height(40)))
             {
                 script.AssignIds();
             }
         }
         else
         {
             GUIStyle style = GUI.skin.box;
             style.normal.textColor = Color.yellow;
             style.fixedHeight = 40;
             style.stretchWidth = true;
             style.alignment = TextAnchor.MiddleCenter;
 
             GUILayout.Box("Add Elements to the list to enable this button", style);
         }
     }
 }
 


113.png (28.1 kB)
112.png (12.8 kB)
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by eladiozro · Jun 25, 2021 at 06:01 AM

What I did is this:

 public class Example {
         public float value_a = 1.0f;
         public float value_b = 1.0f;
         public Example(float a, float b)
         {
             value_a  = a;
             value_b  = b;
         }
 }


This gives preset properties to the array when there is nothing in the component.

 public Example [] inputs = new Example [] { new Example (0.5f, 0.5f) };





Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

83 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

Editor Script Reverts to Default State on Script Compilition 2 Answers

How do I make child classes in a list editable from the Inspector? 1 Answer

How to check if vector in array was not changed? 1 Answer

How to let multiple values contribute two one value constantly 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges