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

Creating an Array

Discussion in 'Scripting' started by Timebreaker900, Jun 30, 2020.

  1. Timebreaker900

    Timebreaker900

    Joined:
    Jun 30, 2020
    Posts:
    1
    Hi I'm new to Untiy and I try to fill an array so that it looks like this:

    0:
    ["human", "Harry", 1, 1]
    1:
    ["elf", "John", null, null]

    So basically that there are multiple elements on one index and I also want to call it in another Script.

    My approach was:

    Creating a Class with the Variables:
    Code (CSharp):
    1. public class PlayerArmy
    2. {
    3.     public int Humans;
    4.     public string Name;
    5.     public int WeaponDmgMin;
    6.     public int WeaponDmgMax;
    7.    
    8. }
    And then I try to fill the array:
    Code (CSharp):
    1. public class ArmyArray : MonoBehaviour
    2. {
    3.     PlayerArmy[] playerArmyArray = new PlayerArmy[4];
    4.     public void Start()
    5.     {
    6.      
    7.         playerArmyArray[0].Humans = 1;
    8.         playerArmyArray[0].Name = "Harry";
    9.         playerArmyArray[0].WeaponDmgMin = 1;
    10.         playerArmyArray[0].WeaponDmgMax = 1;
    11.     }
    12. }
    And in another class I want to call this array but I don't know how to do that.

    So I want 3 Scripts. The first one is the Dataholding one, the second one should fill the array and the last one should call the arrayvalues.

    Thanks in advance!
     
    Last edited: Jun 30, 2020
  2. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    You are initializing the array with empty objects.

    Code (CSharp):
    1.  
    2. PlayerArmy[] playerArmyArray = new PlayerArmy[4];
    3. public void Start()
    4. {
    5.     playerArmyArray[0] = new PlayerArmy();
    6.     playerArmyArray[0].Humans = 1;
    7.     playerArmyArray[0].Name = "Harry";
    8.     playerArmyArray[0].WeaponDmgMin = 1;
    9.     playerArmyArray[0].WeaponDmgMax = 1;
    10. }
     
    Timebreaker900 likes this.