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

Add GameObject in an array through code.

Discussion in 'Scripting' started by stringHakunaMatata, Mar 7, 2021.

  1. stringHakunaMatata

    stringHakunaMatata

    Joined:
    Mar 7, 2021
    Posts:
    3
    In simple words what I am trying to do is, Add GameObject/s in an array through OntriggerEnter and if the GameObjects goes out of the cart then it should be removed from that array on OntriggerExit.

    Note : Array should also increase the size by 1 whenever the gameobject enters it and decrease the size by 1 whenever the gameobject gets removed.
    I am really new to programming so be sure to explain your answers
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    Arrays are immutable in size. You can change their content but you cannot resize them without making an entirely brand-new array. This means they are not well-suited to the application you describe above.

    Use a
    List<T>
    instead, which has
    .Add()
    and
    .Remove()
    methods:

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0

    There are other collection types too, such as
    HashSet<T>
    , with more balanced performance adding and removing.

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=net-5.0
     
  3. stringHakunaMatata

    stringHakunaMatata

    Joined:
    Mar 7, 2021
    Posts:
    3

    Thx a lot man, I managed to do it with the List<>. Your examples were really long so i just googled it... Anyway Thx again mate :)
     
    Kurt-Dekker likes this.