Search Unity

how to have a null array in prefab?

Discussion in 'Editor & General Support' started by khoowaikeong, Nov 16, 2017.

  1. khoowaikeong

    khoowaikeong

    Joined:
    Jun 13, 2013
    Posts:
    18
    I have this class, a simple MonoBehaviour. and it has a public array.
    I need for it to be null. but an empty array 0 length array always pop up during runtime.
    I tried array = null, but prefab seem to disagree with me when it create a new instance.

    did I accidentally serialize some default value into the prefab?
    but removing array from the editor isn't possible since there is no option for null.
    or is it because public variable are always serialized and it cannot be null?
    I don't know, if anyone know this behavior of the editor, pls give me some clue.

    my solution now is to add array.GetLength(0)<1 to catch these weird empty array.
    but it still strike me as bad coding, if anyone has a better solution pls help!
     
  2. sebastiansgames

    sebastiansgames

    Joined:
    Mar 25, 2014
    Posts:
    114
    Null just means it doesn’t exist. When you declare your public array you are making a zero length array ready to do your bidding. But it is a zero length array— it is not nothing! The question is, if you need an array to be null (nothing), why do you have it to begin with?

    Perhaps a solution is to remove the array from your script and then only create one in a function when you need it. I think it’d be easier to help you if we knew what you were doing with this array and why you think you need it to be ‘null’.
     
  3. khoowaikeong

    khoowaikeong

    Joined:
    Jun 13, 2013
    Posts:
    18
    i set it as null during initialization. check the constructor "if array==null" and it return true, but when the object is cloned, it is no longer null. afaik, zero length array isn't nothing, it still take up memory which is why i intentionally use null.

    this is important because the object is intended to build the array on the fly, if it thinks there is an array, it will not create a new array. the array can be remove (set to null) to inform the game that it need to make a new array. it has to stay in memory because it function as a lookup table, if it is null, the code will search for it directly instead and build a new array after finding it.