Here is the function, and when I print the distance, it is always equal to zero, as opposed to being equal to the int i returned from the FindDist
coroutine. However, if I define distance as a public variable outside the function, it will be equal to i
, as returned from the FindDist
coroutine.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public int distance_public = new int();
IEnumerator FindDist(System.Action<int> callBack)
{
for (int x = 0; x < 4; x++)
{
if (x == 3)
{
yield return x;
callBack(x);
break;
}
}
}
string get_hit_chance()
{
int distance = 0;
StartCoroutine(
FindDist((int i) => {
distance = i;
distance_public = i;
})
);
print(distance);
print(distance_public);
float chance = 70 * (100 - distance * distance) / 100;
chance = Mathf.Floor(chance);
return chance.ToString() + "%";
}
void Update()
{
print(get_hit_chance());
}
}
Why is this happening and how can I make the distance equal to i
without defining it outside the get_hit_chance()
function, by this i mean distance_public in this case.
i tested this code and it prints in order 0, then 3, then 0 % hence showing that the class-level variable changes and the local variable doesnt