Question by
wolftek3 · Sep 24, 2019 at 07:01 PM ·
c#instantiatedestroyarrays
Instantiate Previous Prefab in Array
I have a script that instantiates and destroys prefabs in an array. This script moves to the next prefab in the array, and seems to work fine.
using UnityEngine;
public class RayCastNext: MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex++;
currentIndex = currentIndex >= Spheres.Length ? 0 : currentIndex;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
}
My question is, how do I instantiate the PREVIOUS prefab in the array? I have tried currentIndex--; but it does not seem to work - it still moves to the next prefab and not previous.
Any help greatly appreciated.
Comment