0
\$\begingroup\$

I have this code and I know what it does (it will move an object up and down)

But I don't know how its elements work. Could someone please explain it to me?

IEnumerator Move (Vector3 Target) // What this IEnumerator do?
{
    while (Mathf.Abs ((Target - transform.localPosition).y) > 0.1f) {
        Vector3 Direction = Target.y == Top.y ? Vector3.up : Vector3.down;
        //Is this an if/else? and if yes why if target.y == top.y its first choice is vector3.up?

        transform.localPosition += Direction * 5 * Time.deltaTime;
        yield return null;
    }
    yield return new WaitForSeconds(1f);
    Vector3 newTarget = Target.y ==Top.y ? Bottom : Top; 
    //Same line but result order is different ?.?

    StartCoroutine(Move(newTarget)); 
}
\$\endgroup\$
2
\$\begingroup\$

I assume the lines you don't understand are those you put comments on, so I will explain them in order.

  1. A method returning an IEnumerator is one which can use the yield instruction to return values to the caller. Whenever the program flow reaches a yield, the program flow goes back to the caller. The caller can then process that value and then resume the execution of the enumerator-method after the yield instruction (or not). When you encounter such a method in a Unity project, then it is usually used for a Coroutine. The yield return's in a coroutine are the points where the program flow returns to the engine which will then resume the coroutine at a later time (how much later depends on what value you yield return).

    Unity Coroutines can be an elegant way to express processes which are supposed to take multiple frames to complete without having to add complicated state-determination logic to your Update methods or opening up the box of pandora which is actual multi-threading (I personally prefer state machines, command queues and behavior trees, but that's a personal preference).

  2. The a ? b : c construct in C# is the Ternary Condition Operator. It returns a single value. If a is true, it returns b, otherwise it returns c. In this case a is Target.y == Top.y. So in plain English, this line means "If Target.y is equal Top.y, Direction is up, otherwise Direction is down".
  3. And so, Vector3 newTarget = Target.y ==Top.y ? Bottom : Top; means "If Target.y is equal Top.y, then head towards Bottom, otherwise head towards Top"
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.