I am working on an educational kids game. Teaching materials should horizontally scroll one by one, together with the related audio files. For example, if the cat image is on the screen, then the cat sound plays.
I am trying to use coroutines. But GameObjects aren't destroyed individually. All of the previously spawned GameObjects are waiting for the new spawning GameObjects and they are being destroyed at once after all GameObject spawns.
[SerializeField] private GameObject[] sceneObjects;
[SerializeField] private int objectSlideSpeed;
[SerializeField] private int timer;
[SerializeField] private float targetLocation;
void Update()
{
StartCoroutine(SlideLeft());
}
IEnumerator SlideLeft()
{
for (int i = 0; i < sceneObjects.Length; i++)
{
while(sceneObjects[i].transform.position.x > targetLocation)
{
sceneObjects[i].transform.Translate(objectSlideSpeed * Time.deltaTime * Vector3.left);
yield return new WaitForSeconds(timer);
if (sceneObjects[i].transform.position.x < targetLocation)
{
StopSlide(); // objectSlideSpeed = 0;
Destroy(sceneObjects[i]);
}
}
}
}
Expected
Different GameObjects are supposed to be spawned in every second which is specified in
int timer
.Every GameObjects must reach to the target transform position.
At this position, the GameObject must wait without any speed and then the related sound plays. (
Audio.Play()
function will be implemented in theStopSlide()
function later)After sound plays, the GameObject must be destroyed and the different one is supposed to be spawned.
Without destroying the previous GameObject, the new one mustn't be spawned.
Destruction and spawning methods don't require any user actions. They occur automatically depending on the
timer
variable.
Current Situation
- The first GameObject is spawned and it reaches the target transform position which is specified in the
float targetLocation
variable. - At this point, the first GameObject waits for a specified second without any speed.
- Meanwhile, the new and different GameObject is spawned and after it reaches the target location either, all of spawned GameObjects are destroyed altogether.