0

I'm trying to write the following functionality (implemented in the code snippet below). On a button click, the async function openUnityProjectScene is called. This function should set a loading view and await a state boolean - unityInstanceIsStarted - to be true before firing a message to the Unity instance to open a project scene. The waiting is to be handled by the function waitForUnityInstanceToStart. However, when I run this, if waitForUnityInstanceToStart is called while unityInstanceIsStart is false, unityInstanceIsStart will remain false within the scope of poll, even after state has been set to true and is reflected as so elsewhere in the component. This was not expected behavior based on my own intermediate experience with JS and the examples of similar waitFor functions I've found while researching.

Here's my code. It's not pictured, but setUnityInstanceIsStarted is subscribed elsewhere as an listener to an event fired out of the Unity instance. It's being called and updating state as expected.

const [ unityInstanceIsStarted, setUnityInstanceIsStarted ] = useState(false);

function waitForUnityInstanceToStart() {
    const poll = resolve => {
      if (unityInstanceIsStarted) resolve();
      else setTimeout(() => poll(resolve), 500);
    }
    return new Promise(poll);
}

const waitForUnityInstanceToOpenProject = async (projectID) => {
    setEditorView(EditorView.Loading);

    await waitForUnityInstanceToStart()
        .then(() => { sendMessage(reactUnityRelay, "OpenProject", projectID); });
}

Maybe I'm making an obvious mistake, but I'm at a loss. Am I just misunderstanding how scope works here? Is unityInstanceIsStarted somehow passed to the poll arrow function as a value instead of a reference? Is there an alternative method I could use to achieve the desired effect? Thanks in advance for any time and feedback given.

  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad May 09 '23 at 16:32
  • Also https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Konrad May 09 '23 at 16:33

0 Answers0