Search Unity

c# and the best equivalent of #include (from c/c++)?

Discussion in 'Scripting' started by rsud, Jul 21, 2014.

  1. rsud

    rsud

    Joined:
    Aug 13, 2010
    Posts:
    89
    Hello,
    New to c# and wanted a recommendation on how to use a common data variables across multiple .cs files.

    In c/c++ I would put variable definitions into an include file and #include them in the separate c/c++ code source files.

    I just want the same variables in the separate c# classes (.cs).
    But I DO NOT need the variables to share the same value across classes (.cs files).
    Each class will have its own settings for each of the variables.

    What is my best option to do the equivalent in c#?

    Should I just create a class (.cs) with my common variables and then declare each of the class .cs files?
     
  2. TRALLALAL

    TRALLALAL

    Joined:
    Sep 7, 2013
    Posts:
    132
    I would like to know this as well as I'm using different files which share the same things except for values.
     
  3. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    C# is 100% object, you can't have variables hanging in nowhere like in C. You can make singleton classes & static variables if you want it quick and simple, or use various design patterns to locate your data etc...

    Also what you say kinda look like you could use inheritance. It would give you a base class to derive from your other classes that have the same root.
     
  4. landon912

    landon912

    Joined:
    Nov 8, 2011
    Posts:
    1,579
    You could extend MonoBehavour with your variables in a custom class and then use that as your base class for everything else.
    Code (CSharp):
    1. class CustomMonoBehaviour : MonoBehaviour
    2. {
    3.           //fields you want to inherit in other classes
    4. }
    5.  
    6. class EveryOtherClass : CustomMonoBehaviour
    7. {
    8.  
    9. }
    Or, you could use interfaces if you only need methods, properties, or events.
     
  5. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    The easiest way to do this is to have a base class that contain that variable and then have all the other classes inherit from that.
     
    WhoRainZone1 likes this.
  6. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    Base class for the definition with a constructor to set the variables to the values you want per derived type?
     
    WhoRainZone1 likes this.
  7. WhoRainZone1

    WhoRainZone1

    Joined:
    Oct 6, 2013
    Posts:
    15
    Just for some backup - base class is what you want, and my above posters already said so