Can I instantiate objects from an array 1 at a time?
I have a scripted object that instantiates objects from an array when it collides with something. That part working with this:
GameObject[] biasBar;
public int barNumber;
private void OnTriggerEnter2D(Collider2D other) { if(other.tag == "Object1") { Instantiate(bar[barNumber++], new Vector3(6, -4, 0), Quaternion.identity); } if(other.tag == "Object2") { Instantiate(bar[barNumber--], new Vector3(6, -4, 0), Quaternion.identity); } }
The problem is that I only want to have one object from the array on the screen at a time. Is there a way can I delete the current array object once the new array object is instantiated?
Answer by Hellium · Jul 19, 2019 at 03:39 PM
GameObject[] biasBar;
public int barIndex;
private GameObject instance;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Object1"))
{
if (instance != null) Destroy(instance);
barIndex = Mathf.Min(barIndex + 1, biasBar.Length);
instance = Instantiate(biasBar[barIndex], new Vector3(6, -4, 0), Quaternion.identity);
}
if (other.CompareTag("Object2"))
{
if (instance != null) Destroy(instance);
barIndex = Mathf.Max(barIndex - 1, 0);
instance = Instantiate(biasBar[barIndex],new Vector3(6, -4, 0), Quaternion.identity);
}
}
Your answer
Follow this Question
Related Questions
Trying to spawn enemies on only one path 1 Answer
Spawning limited GameObjects at a specific position not working 1 Answer
I want to make make a plant to grow after few seconds. 0 Answers
Question about Array indexing 0 Answers
Instantiate players in Photon. Error: Index was outside the bounds of the array. 1 Answer