- Home /
Swap and cycle through game objects using an array
I am trying to swap and cycle through game objects. I have an array of game objects that are projectile attacks. I want the user to be able to press a button and swap out the current three game objects with the next three game objects in the array. When the last three are reached, I want to start the cycle over again. Basically it is like switching weapon loadouts on the fly. I have tried a few ways to do this (my switch statement failed horribly), but none have worked so far. Now I am running low on ideas. Any suggestions/tips/hints for how to handle something like this will be extremely helpful. Below is some code to look at if it helps you to get an idea of what I am trying to do.
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public GameObject[] attackArray = new GameObject[6];
public int shotPosX;
public int shotPosY;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
GameObject attack = attackArray[0];
GameObject attackDown = attackArray[1];
GameObject attackUp = attackArray[2];
if(Input.GetButtonUp("Fire1") == true)
{
Instantiate(attack, new Vector3(transform.position.x + shotPosX, transform.position.y - shotPosY, transform.position.z), transform.rotation);
}
if(Input.GetButtonUp("Fire2") == true)
{
Instantiate(attackUp, transform.position, transform.rotation);
}
if(Input.GetButtonUp("Fire3") == true)
{
Instantiate(attackDown, transform.position, transform.rotation);
}
}
}
Answer by Vonni · Sep 03, 2013 at 07:51 PM
This wont compile :P But should be a reasonable way of doing it. You could ofcourse also just have 3 arrays, 1 for each weapon "slot?".
int collectionSet = 0; // When zero the first three gameobjects in your array will be used as fire 1,2,3...
public GameObject[] attackArray = new GameObject[6];
update ()()()()(
if(hit button that switches set of weapons)
if(collectionSet is attackArray.Length - 2)
collectionSet = 0;
else
collectionSet += 3;
if( hit fire1)
Instantiate(attack[collectionSet] // attack.... // etc....
if( hit fire2)
Instantiate(attack[collectionSet + 1] // attackUp.... // etc....
if( hit fire3)
Instantiate(attack[collectionSet + 2] // attackDown.... // etc....
Thank you very much. This was extremely helpful. With a very slight adjustment, this works like a charm for what I wanted to do.
Your answer
Follow this Question
Related Questions
Checking if a position is occupied in 2D? 1 Answer
Get all other GameObjects (not the one script is attached to) 2 Answers
Adding GameObject to GameObject[] array 1 Answer
Array out of index? 1 Answer