Search Unity

Question List, Initialize and public variables

Discussion in 'Scripting' started by Lorrak, Jun 11, 2021.

  1. Lorrak

    Lorrak

    Joined:
    Sep 17, 2019
    Posts:
    50
    Hello,
    i have few prefabs in folder, and this script is attached to game object in scene, i mount my prefabs in the game object's Inspector window, and if I initialize List in start() method all my prefab mounting is gone, would it be ok not initialize List in start() method and delete the line

    i read somewhere if variable is Public, Unity automatically initialize it?

    Code (CSharp):
    1. public class Testing : MonoBehaviour
    2. {
    3.     public List<GameObject> myPrefabs;
    4.  
    5.     private void Start()
    6.     {
    7.         myPrefabs = new List<GameObject>();    // don't need this  
    8.     }
    9. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    More precisely, certain types of public variables may be serialized by Unity.

    If they are serialized, then after the class is constructed, Unity will initialize it.

    Details:

    https://docs.unity3d.com/Manual/script-Serialization.html

    So yes, you would not want the code above because line 7 will wipe out any objects you saved in your scene via serialization.
     
    Lorrak and Bunny83 like this.