How to add Gameobject into array?

Hello,
I have defined array like this:

public GameObject[] object = new GameObject[1];

How do i add a gameobject into this array in Start method ?

EDIT

I have this method

void addToArray(Equipment newItem)
{
    for (int i = 0; i < lasers2.Length; i++)
    {
        lasers2[i] = newItem;
    }
}

But then when i add newItem into array it adds newItem into every array object.

2 Answers

2

What you need to know is that C# arrays (GameObject[] for example) can NOT change it’s size once created. What you need is a generic class List<T> - a collection/list that can change size.

// List<T> is part of this namespace
using System.Collections.Generic;

// field declaration
public List<Equipment> equipmentList = new();

// this is how you add an item
equipmentList.Add( newItem );

Thats why i want to use array, i need is size to be fixed

Why addToArray() then? InsertAtArrayIndex( item , index ) would make more sense

Can you post full method for InsertAtArrayIndex( item , index ), please?

Sure. It's simply myArray[index] = item;. But be aware that this will throw an IndexOutOfRangeException every time index>=myArray.Length.

Like this void InsertAtArrayIndex(Equipment newItem, int index) { lasers[index] = newItem; } Then how do i call this method?

Hi,
You must be careful in your definition, if you say

public GameObject object = new GameObject[1];

It mean that you’re going to instantiate a array with only one spot for a element (or GameObject in your case) and if you try to add more object than there is a sport for, you should get an error.


I don’t understand what you’re trying to mean here :

But then when i add newItem into array it adds newItem into every array object.

Sorry about that but can you explain again or/and give us more information about your code ?

I have 4 equipment slots in my array for my items. When i try to add newItem it adds item in every equipments slot with my code, and i need to add this 1 by 1 in 1, 2nd, 3rd etc slots.