To keep track of what objects you instantiated you could create a List of GameObject and then when you instantiate an object you can add it in the List. Then you can use any GameObject in that list to do whatever you need.
public GameObject[] arrows;
public float interval = 5;
private List<GameObject> myObjects = new List<GameObject>();
// Use this for initialization
void Start()
{
StartCoroutine(SpawnArrow());
}
public IEnumerator SpawnArrow()
{
WaitForSeconds delay = new WaitForSeconds(interval);
while (true)
{
GameObject prefab = arrows[UnityEngine.Random.Range(0, arrows.Length)];
GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);
//Add the object to the list
myObjects.Add(clone);
yield return delay;
}
}
And for spawning object like that it would be better to use InvokeRepeating, you can pass it the repeat rate and when you want it to start. More information on InvokeRepeating
This is how it could look like with InvokeRepeating
public GameObject[] arrows;
public float interval = 5;
private List<GameObject> myObjects = new List<GameObject>();
// Use this for initialization
void Start()
{
InvokeRepeating("SpawnArrow", 0f, interval);
}
void SpawnArrow()
{
//Check if there's something in the list
if (myObjects.Count > 0)
{
//Destroy the last object in the list.
Destroy(myObjects.Last());
//Remove it from the list.
myObjects.RemoveAt(myObjects.Count - 1);
}
GameObject prefab = arrows[UnityEngine.Random.Range(0, arrows.Length)];
GameObject clone = Instantiate(prefab, new Vector3(0.02F, 2.18F, -1), Quaternion.identity);
//Add the object to the list
myObjects.Add(clone);
}
You can destroy the last spawned object in the list by doing Destroy(myObjects.Last()); it will return the last object in your list and destroy it. You should then also remove it from the list myObjects.RemoveAt(myObjects.Count - 1);
YourOtherFunction(clone)in the while loop. If that is not what you are looking for you need to provide more deatail about what you are trying to do. Include the other function too in your code example.