Singular System.Threading.Channel reference returns multiple instances in different Methods

25 Views Asked by At

This question is an extension of: Awaited TaskCompletionSource and Channel Reader doesn't resume when SetResult/Write in Update

In a singular unity script, I have a structure like below (simplified from original for conciseness):

private readonly Channel<GameObject> selection = Channel.CreateUnbounded<GameObject>();

public async Task<GameObject> AwaitedFromAnother()
{
    GameObject obj = await selection.Reader.ReadAsync(); //Read From Channel
    return obj;
}

private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        GameObject DO = DetectValObj(); //Helper Method for Raycast Object Detection...
        if (DO)
        {
            selection.Writer.TryWrite(DO); //Write Into Channel
        }
    }
}

AwaitedFromAnother() is awaited from a different object's component, and it's supposed to await the input from Update() below. However, even when I click on a valid object and trigger selection.Writer.TryWrite(DO) (I checked by calling selection.Reader.TryPeek() right after), AwaitedFromAnother() still remains stuck on await selection.Reader.ReadAsync() most of the time.

I checked if I was writing to and reading from a valid Channel, and as it turns out that there are multiple instances of Channel<GameObject> under the same reference of selection. Multiple checks of GetHashCode() revealed that they were two different Channel<GameObject> in both AwaitedFromAnother() and Update().

The Object this script is attached to is in the initial scene to begin with, so there aren't any code instantiating the component instance.

Why would a singular Channel<GameObject> reference house two different instances of Channels, and how do I force it to definitely be singular throughout the script?

0

There are 0 best solutions below