I want to assign to a ref variable from inside a lambda. This is a simplified MRE of what I have:
public class Foo
{
public int Value { get; private set; }
public Foo(int value) => this.Value = value;
}
public class Test
{
Foo F1 = new Foo(1);
Foo F2 = new Foo(2);
// library method, cannot change
void LoadAsync(int value, Action<Foo> onSuccess)
{
// this happens async on a future frame
Foo f = new Foo(value);
onSuccess(f);
}
// my method, can change parameters and body, cannot change return type
void LoadAndAssignAsync(int value, ref Foo fooToAssign)
{
LoadAsync(value, loadedFoo => fooToAssign = loadedFoo); // this is not allowed
// because the load happens async, I cannot assign `fooToAssign` here,
// it needs to happen inside the lambda
}
void Start()
{
LoadAndAssignAsync(11, ref F1); // I want to keep this simple
LoadAndAssignAsync(24, ref F2);
// I want a simple way of saying:
// load and when done assign the result to the variable (field) I specify
}
}
Because of the reasons shown here a lambda cannot capture a reference variable. I am looking for a simple alternate method, if it exists.
I can change and pass a lambda instead LoadAndAssign(11, result => F1 = result
, but it is cumbersome, I am hoping I can keep the simple ref F1
argument.
async here means Unity's "async", aka coroutines, more specifically Addressables' AsyncOperationHandle