The question is answered, right answer was accepted
Nothing after coroutine gets executed
I am trying to move my player character to a certain point(targetPoint) but only on the x-axis. I am using a coroutine, and the character moves to the point, but after that nothing else gets executed (As an example: "Debug.Log("Hi3")"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LevelLoader : MonoBehaviour
{
public string newScene, oldScene;
public Vector3 playerChange, cameraChange;
GameObject player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
player.GetComponent<PlayerMovement>().canWalk = false;
StartCoroutine("loadLevel_movePlayer_unloadLevel");
}
}
IEnumerator loadLevel_movePlayer_unloadLevel()
{
Debug.Log("Hi1");
SceneManager.LoadScene(newScene, LoadSceneMode.Additive);
Vector3 targetPoint = new Vector3(playerChange.x,
player.transform.position.y,
playerChange.z);
Debug.Log("Hi2");
while (player.transform.position.x != playerChange.x)
{
player.GetComponent<Rigidbody2D>().transform.position = Vector3.Lerp(player.transform.position,targetPoint,0.01f);
yield return null;
}
yield return 0;
Debug.Log("Hi3");
}
}
Answer by BradyIrv · Aug 06, 2019 at 01:56 PM
It's probably that when checking against floats they will never be exactly the same so your coroutine is getting stuck on the while loop before "Hi3".
You can try:
while (Vector3.Distance(player.transform.position, playerChange) > 1f)
then again that "yield return 0" could also be an issue and ending the coroutine before the Debug execution
Follow this Question
Related Questions
Coroutine: delay transform rotation but start transform movement immediately 2 Answers
Coroutine doesn't continue after yield another coroutine 0 Answers
Unity WaitForSeconds Not Working Inside Update or a Loop 2 Answers
StartCoroutine not listening to parameters 1 Answer
Execute coroutine in Update() 8 Answers