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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Class arrays

Discussion in 'Scripting' started by Eidern, Apr 18, 2018.

  1. Eidern

    Eidern

    Joined:
    Mar 29, 2014
    Posts:
    94
    Hello i got a simple public class ,
    but I don't understand how can I add multiple objects as an array of that class.


    As it's public, in the editor I've set the size of the entities array, but I still can't create objects.
    I'm missing the obvious :/

    Code (CSharp):
    1.     public class entity{
    2.         public string name;
    3.        ..
    4.     }
    5.     public entity[] entities;
    6. entities[0].name="foobar"; //returns error "NullReferenceException: Object reference not set to an instance of an object"
    7.  
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you haven't instantiated anything into the [0] slot.

    Code (csharp):
    1.  
    2. entities[0] = new entity();
    3.  

    edit: you've also not created or specified the size of the array, only declared it

    Code (csharp):
    1.  
    2. public entity[] entities = new entity[10]; // 10 slots
    3.  

    https://www.dotnetperls.com/array
     
    TaleOf4Gamers and Eidern like this.
  3. Eidern

    Eidern

    Joined:
    Mar 29, 2014
    Posts:
    94
    In the unity editor, I see in the inspector the Entities , and i set the value to 5.
    Sot it equals to public entity[] entities = new entity[5];

    But I thought that declare it in the inspector implicitly instantiate it :/
    so I needed to instantiate it first,
    thanks again