My coroutine won't work
So I have two separate scripts that have methods that are called whenever a certain object is clicked. One of them, however, needs a static variable from the other script to be assigned (PlayerHippoController.hippoSelected) before it can continue on. So I made a coroutine that should keep the rest of the code at bay until the variable has been assigned. This is my code, most of which can be ignored besides OnMouseDown() and WaitForHippoSelected().
public class Space : MonoBehaviour {
public float timeToMoveSpaces = 1.5f;
private bool isMovingSpaces;
private Vector3 startPosition;
private Vector3 endPosition;
private float timeStartedMovingSpaces;
void OnMouseDown () {
StartCoroutine (WaitForHippoSelected ());
foreach (GameObject space in PlayerHippoController.hippoSelected.GetComponent<PlayerHippoController> ().availableSpaces) {
if (gameObject == space) {
StartMovingSpaces ();
}
}
}
void StartMovingSpaces () {
PlayerHippoController.hippoSelected.transform.parent = gameObject.transform;
isMovingSpaces = true;
timeStartedMovingSpaces = Time.time;
startPosition = PlayerHippoController.hippoSelected.transform.position;
endPosition = gameObject.transform.position;
}
void FixedUpdate () {
if (isMovingSpaces) {
float timeSinceStartedMoving = Time.time - timeStartedMovingSpaces;
float percentageComplete = timeSinceStartedMoving / timeToMoveSpaces;
PlayerHippoController.hippoSelected.transform.position = Vector3.Lerp (startPosition, endPosition, percentageComplete);
if (percentageComplete >= 1) {
isMovingSpaces = false;
}
}
}
IEnumerator WaitForHippoSelected () {
while (PlayerHippoController.hippoSelected == null) {
yield return null;
}
}
}
So, for some reason, whenever I try to access PlayerHippoController.hippoSelected, I get an error because it's never assigned. Through testing, I found out that the while loop in WaitForHippoSelected() continues to loop forever and doesn't stop. However, for some reason, the code after the coroutine is called gets called instead of being paused, and I can't figure out why. That right there is my main problem, and I can't figure out why the coroutine isn't delaying the rest of the code.
Your answer
Follow this Question
Related Questions
Coroutine only works one way 1 Answer
How to get a for loop to run once per coroutine? 0 Answers
Unity Freezing after for loop 1 Answer