Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Editor only fields using #if UNITY_EDITOR

Discussion in 'Scripting' started by Alex-Chouls, Jul 29, 2021.

  1. Alex-Chouls

    Alex-Chouls

    Joined:
    Mar 24, 2009
    Posts:
    2,651
    I'm trying to get a definitive answer on if this is acceptable:

    Code (CSharp):
    1. public class Test : MonoBehaviour
    2. {
    3.     [SerializeField] int intField;
    4.  
    5.     #if UNITY_EDITOR
    6.     [SerializeField] string editorOnlyField;
    7.     #endif
    8.  
    9. }
    When I've tried this in the past it's resulted in serialization layout errors on some platforms.

    But there's newer info like this implying it's been fixed:
    https://github.com/Unity-Technologies/guid-based-reference/issues/2

    Other threads asking for more documentation trail off without answers:
    https://forum.unity.com/threads/add...fields-inside-preprocessor-directives.715319/

    Indeed, there seem to be many threads asking about this with no clear official answers.

    I also can't find anything at all about it in the docs - if it's allowed or not allowed, and no mention of serialization layout errors and what they mean.

    Any chance we could put this to rest with an official answer? Workarounds for editor only data can get quite convoluted, so it would be nice to know if the simple/clean solution actually works.
     
  2. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    2,554
    From the tests that I've done it works as expected in normal scripts but doesn't work on scripts defined in pre-compiled DLLs. But yeah, it would be nice to see an official explanation instead of ... my own post from 2018.
     
  3. Alex-Chouls

    Alex-Chouls

    Joined:
    Mar 24, 2009
    Posts:
    2,651
    Thanks for the info. I almost contacted you directly because of your posts :) Have you tested on AOT platforms?
     
  4. Kybernetik

    Kybernetik

    Joined:
    Jan 3, 2013
    Posts:
    2,554
    I mostly use Android in IL2CPP mode, but I don't specifically remember testing or even using editor-only fields there. I'm pretty sure I did the original testing on PC builds.
     
  5. steinbitglis

    steinbitglis

    Joined:
    Sep 22, 2011
    Posts:
    254
    Last edited: Jun 15, 2023