Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

An Array of a class

Discussion in 'Editor & General Support' started by Vanz, Jul 16, 2014.

  1. Vanz

    Vanz

    Joined:
    Nov 19, 2013
    Posts:
    374
    I have a class defined as:

    Code (csharp):
    1.  
    2. class PlayerXClass
    3.   {
    4.   public float[] LevelScore = new float[12];
    5.   public int TotalScore, PlayerHand;
    6.   }
    7.  
    This is defined before “MonoBehaviour {“

    How do I now get an array of “4” Players from this, I tried this:

    Code (csharp):
    1.  
    2. PlayerXClass[]   PlayerX = new PlayerXClass[5];
    3.  
    Which is located after “MonoBehaviour {“, but before “Awake()”

    Then I define an instance in "Awake()" as:
    Code (csharp):
    1.  
    2. PlayerX[1].TotalScore = 0;
    3.  
    MonoBehaviour compiles the program with no errors but Unity gives the error “NullReferenceException: Object reference not set to an instance of an object Initialize_Multiplayer.Awake () (at Assets/Initialize_Multiplayer.cs:43)”
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Code (csharp):
    1.  
    2. // Declare it
    3. PlayerXClass[] PlayerX = new PlayerXClass[4];
    4.  
    5. // Before you use it, you need to create it
    6. PlayerX[0] = new PlayerXClass ();
    7. PlayerX[0].TotalScore = 0;
    8.  
     
  3. Vanz

    Vanz

    Joined:
    Nov 19, 2013
    Posts:
    374
    ooohh, thanks...