Search Unity

Question on public classes

Discussion in 'Scripting' started by Beginner_at_Unity, Sep 5, 2019.

  1. Beginner_at_Unity

    Beginner_at_Unity

    Joined:
    Jul 5, 2019
    Posts:
    179
    I already started my basic c# tutorial in https://www.learncs.org/en/Basic_Classes. I tried to modify a class by making it public. SEe my screenshot. Why am I getting errors? The code changed to comments are original but my understanding is since the class has been made public, the code should be accessible from another class. Yet it cannot be accessed. Why can't it be accessed?
     

    Attached Files:

  2. Harfatum

    Harfatum

    Joined:
    May 28, 2018
    Posts:
    9
    By default, class variables are private. You will have to give each one the "public" keyword to make them public.
     
  3. Beginner_at_Unity

    Beginner_at_Unity

    Joined:
    Jul 5, 2019
    Posts:
    179
    TQ.
     
  4. GameDevCouple_I

    GameDevCouple_I

    Joined:
    Oct 5, 2013
    Posts:
    2,219
    @JulianHSC

    To build on what was said above, anything in C# has to have its access defined. Anything that does not will be private unless specified to be something else.

    So you can have a public class, where the class is accessible to other bits of code, but the actual variables inside might be private so you cant see them.

    You could also have a public class with a private class inside it. Etc etc.

    So if you ever struggle to access something, check what access modifier you have given it.

    Im not going to go into what "protected" is as you likely wont be doing inheritence for a bit, but if you ever start to learn about "inheritance" then please do message back on here and I will give you a rundown of how that works and why and when you may use it.

    The same for "static", right now you probably wont need that keyword but if you start to come across it and its not explained in your tutorials then please do message back on here.
     
  5. Beginner_at_Unity

    Beginner_at_Unity

    Joined:
    Jul 5, 2019
    Posts:
    179
    TQ. Earlier the moderator mentioned that I can open multiple threads but make sure they aren't duplicates. I'll ask further if I have questions.