Search Unity

Question about JavaScript Classes

Discussion in 'Scripting' started by CgRobot, Mar 1, 2012.

?

How often do you use classes?

  1. Always! I couldn't make a game without them.

    100.0%
  2. Quite a bit, but not too frequently.

    0 vote(s)
    0.0%
  3. Rarely. They're not that useful.

    0 vote(s)
    0.0%
  4. Never.

    0 vote(s)
    0.0%
  1. CgRobot

    CgRobot

    Joined:
    Jan 4, 2011
    Posts:
    175
    Hey everyone. I have a question about classes in JavaScript. I know how to use them in the code but I want to know how often you guys use them in your games as well as when they are most helpful and when they are just overkill. I had considered making a game that has several reusable game objects with very extensive code with a lot of parameters and I thought that creating a class for these objects would be the best thing to do, but I'm not sure. Also, if I did create a class in one JavaScript file, could it be easily accessed from another script? Any recommendations, advice, or links to helpful material is welcomed. Thanks.
     
  2. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    868
    I'm curious what your definition of 'class' is - it's literally impossible to do anything in Unity without using a 'class' - are you talking about a subclass of object, or custom subclasses of MonoBehaviour in general?
     
  3. CgRobot

    CgRobot

    Joined:
    Jan 4, 2011
    Posts:
    175
    An example of what I'm talking about is this:

    Code (csharp):
    1.  
    2. class className
    3. {
    4.         //Define lots of variables here
    5. }
    6.  
    I guess it would be a subclass of MonoBehavior.
     
    Last edited: Mar 2, 2012
  4. Eiznek

    Eiznek

    Joined:
    Jun 9, 2011
    Posts:
    374
    If your talking about custom classes they don't have to be a subclass of monoBehavior. You can simply make a Datatype..

    Ex:
    Code (csharp):
    1.  
    2. [System.Serializable]
    3. public class PlayerData()
    4. {
    5.    public string playerName;
    6.    public int playerCurrency;
    7.    public float playerDamage;
    8.    //Etc..
    9. }
    10.  
    How you could use this is simple just adding a new one of that type in your script..

    Code (csharp):
    1.  
    2. PlayerData myPlayer = new PlayerData();
    3.  
    This is obviously c# though and this would be created in a Monobehavior class that would be added to a gameobject. From there you could do whatever you wanted with the data.

    ** [System.Serializable] makes the Custom class viewable in the inspector.