Unity4 Scripting – Choose / Select from Array

A simple script that cycles through an array

using UnityEngine;
using System.Collections;

public class Selector3 : MonoBehaviour {

public GameObject[] selectionSet;
GameObject selection;
//GameObject nextSelection;
//GameObject previousSelection;
int index = 0;

//Vector3 previousPosition = new Vector3(-1,0,0);
Vector3 selectionPosition = new Vector3(0,0,0);
//Vector3 nextPosition = new Vector3(1,0,0);

// Use this for initialization
void Start () {

selection = Instantiate (selectionSet [index], selectionPosition, Quaternion.identity) as GameObject;

}

// Update is called once per frame
void Update () {

if(Input.GetKeyDown(KeyCode.RightArrow)){

Destroy(selection);

if(index < (selectionSet.Length – 1)){ index++; } else { index = 0; } selection = Instantiate (selectionSet [index], selectionPosition, Quaternion.identity) as GameObject; } if(Input.GetKeyDown(KeyCode.LeftArrow)){ Destroy(selection); if(index > 0){
index–;
} else {
index = (selectionSet.Length – 1);
}

selection = Instantiate (selectionSet [index], selectionPosition, Quaternion.identity) as GameObject;
}

}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s