0

I was wondering how I could make an array of game objects using only one image? For example, I have a picture of a cannon ball and a cannon and I want to make 10 cannon balls and be able to change each one of them individually. I have this script attached to a single cannon ball gameobject and I have made my array length 5 using the inspector.

I've tried using instantiate but all that happens is it clones it forever.

public GameObject[] cannonball;
public int i;
public int x=0;
void Start()
{
    for (i = 0; i < cannonball.Length; i++) {
        Instantiate(cannonball[i], new Vector2(x, 0), Quaternion.identity);
        x = x + 5;
    } 
}

When I do this, for some reason it continues to clone game objects and I don't know why.

7
  • Yes this is using unity thanks! Commented Jun 5, 2019 at 0:00
  • What kind of object is this script attached to? Commented Jun 5, 2019 at 0:11
  • Well I am in unity 2D so just a sprite Commented Jun 5, 2019 at 0:14
  • I'm curious if it's on a cannonball, if it's on a cannon, or something else. Commented Jun 5, 2019 at 0:21
  • This script is on my cannon ball. I have a cannon gameobject in place and every time I press space I want it to fire a cannon ball. If I press space lets say 3 times, you can see 3 cannon balls moving across the screen. Commented Jun 5, 2019 at 0:23

1 Answer 1

2

You attached this script to a canonball GameObject. This means that everytime you fire a canonball, this will have the script attached to it as well and spawn a new canonball spawning a new canonball... You can see the loop here.

You should not attach this to a canonball prefab, but rather on for example a GameController object.

I haven't tested it, but to do this, create a new GameObject in your scene and attach your script to it after removing it from your cannonball GameObject..Now if you press space you can instantiate the cannonballs.

public GameObject[] cannonball;
public int i;
public int x=0;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space)) {
        for (i = 0; i < cannonball.Length; i++) {
            Instantiate(cannonball[i], new Vector2(x, 0), Quaternion.identity);
            x = x + 5;
        }
    } 
}
Sign up to request clarification or add additional context in comments.

6 Comments

How can I do this
@Trucing Put the script on literally anything else besides your prefab.
Okay, and how can I make each of the cloned objects an image in my array through the inspector?
Or how can I move an instantiated object?
|

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.