0

I have an array in my C# script

GameObjects[] gameObjects

and I have an object

GameObject myObject

I want to create a random number of elements in gameObjects array and add myObject to every element of the array (my object could be cube, sphere or anything) and then Instantiate it on screen. How can I do this?

I already have code below

public GameObject[] myObjects;

void Start()
{
    float x = gameObject.GetComponent<Camera>().transform.position.x - Random.Range(100, 200);
    float y = gameObject.GetComponent<Camera>().transform.position.y - Random.Range(50, 150);
    float z = gameObject.GetComponent<Camera>().transform.position.z + 800;
    Instantiate(myObjects[0], new Vector3(x, y, z), Quaternion.identity);
}

and it works perfectly but with this code, I may only add objects to the array from unity properties but I need to add elements from the code. I found nothing on the Internet about it.

2
  • Does this answer your question? Adding Elements To An Array Using Array.Add Commented Jun 24, 2021 at 19:26
  • I understand it's not your question, but there is no real reason to use an Array over a List<>. The performance gain is minimal. Commented Jun 24, 2021 at 20:09

1 Answer 1

2

It seems that a list might suit your needs better.

If you have to use arrays, you can initialize the size of an array on the Start() method.

public GameObject[] myObjects;

const int maxSize = 20;
const int minSize = 1;

void Start()
{

    int arraySize = Random.Range(minSize, maxSize);
    myObjects = new GameObject[arraySize];

    for (int i = 0; i < arraySize; i++)
    {
        // Be sure to change the positions of each object
        float x = gameObject.GetComponent<Camera>().transform.position.x - Random.Range(100, 200);
        float y = gameObject.GetComponent<Camera>().transform.position.y - Random.Range(50, 150);
        float z = gameObject.GetComponent<Camera>().transform.position.z + 800;
        Instantiate(myObjects[i], new Vector3(x, y, z), Quaternion.identity);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Your code wasn't what I exactly need but thanks to you I understood what I was doing wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.