Constructor and Field relationship in a Coroutine

Hi, in the method below I change the value of the field when a desired condition is met. Is this the correct way ?
It does work as expected and Debug.Log gives correct output. I am confused about the constructor and field relationship when value gets changed inside a method.

private bool isTarget = false;

public void TriggerCoroutine()
{
    StartCoroutine(TestCoroutine(isTarget));
}

IEnumerator TestCoroutine(bool isTargetPos)
{

    if (isTargetPos == false)
    {
        Debug.Log("isTarget = " + isTarget);
        Debug.Log("isTargetPos = " + isTargetPos);
        isTarget = true; // Sets the field value opposite so the next time it would enter the if statement below.
        Debug.Log("isTarget = " + isTarget);
        Debug.Log("isTargetPos = " + isTargetPos); // My concerns is that this still prints as false.

// Even though the constructor has the reference to the isTarget field

    }

    if (isTargetPos == true)
    {
        Debug.Log("isTarget = " + isTarget);
        Debug.Log("isTargetPos = " + isTargetPos);
        isTarget = false;
        Debug.Log("isTarget = " + isTarget);
        Debug.Log("isTargetPos = " + isTargetPos); // My concerns is that this still prints as true.

// Even though the constructor has the reference to the isTarget field
    }
}

There’s no constructors involved here, so you’re probably getting your terminology mixed up.

When you call TestCoroutine with isTarget, you’re not passing a reference to the field isTarget, you’re just passing a copy of the value of the variable.

If you’re trying to toggle the value of isTarget, just do:

isTarget = !isTarget;
2 Likes

Thank you!
and one more Q, isn’t bool “isTargetPos” a constructor parameter of the coroutine “TestCoroutine” ?
IEnumerator TestCoroutine(bool isTargetPos)

No, it’s just a parameter.

class MyClass
{
   public MyClass()
   {
  
   }
}

This is a constructor, which is not allowed on MonoBehaviours or ScriptableObjects because of the way Unity creates your objects.