stingalimian galimian
stingalimian galimian

Reputation: 13

how can I wait for the Initialize() finish then execute the code?

My code needs to wait until the Initialize() then can be execute. I use WaitForSeconds(1.0f) until Initialize() like below , but it saw no good solution.

    IEnumerator waiuntilInit()
    {
        Initialize();
        yield return new WaitForSeconds(1.0f);
        dosomeThing();
    }

how can I wait for the Initialize() finish then execute the code?

void waitInit(){
  wait  Initialize()
  dosomeThing();
}
Initialize()
{
     var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
     builder.Configure<IGooglePlayConfiguration>().SetDeferredPurchaseListener(OnDeferredPurchase);
     builder.Configure<IGooglePlayConfiguration>().SetQueryProductDetailsFailedListener(MyAction);
     builder.AddProduct(productId, ProductType.Subscription);
     UnityPurchasing.Initialize(this, builder);
};

Upvotes: 0

Views: 900

Answers (2)

syp5w2qxe
syp5w2qxe

Reputation: 125

You can use a nested coroutine to accomplish this. Make the Initialize() method also a couroutine then 'yield' from within the first one. I've checked the log output below and it works in the order you are looking for. Good luck :)

    void Start()
    {
        StartCoroutine(waitUntilInit());
    }

    IEnumerator waitUntilInit()
    {
        Debug.Log("1 Wait until Init");
        yield return Initialize();
        Debug.Log("4 Do Something else now");
    }

    IEnumerator Initialize()
    {
        Debug.Log("2 Initialize Start");
        yield return new WaitForSeconds(1.0f);
        Debug.Log("3 Initialize Done");
    }

Upvotes: 0

bartol44
bartol44

Reputation: 562

You could use WaitUntil inside your coroutine.

The code sample for Purchaser script for unity purchasing comes with a method (at least I don't remember writting it myself), that checks if it was initialized:

public bool IsInitialized()
{
    // Only say we are initialized if both the Purchasing references are set.
    return m_StoreController != null && m_StoreExtensionProvider != null;
}

You now got a condition, that you should wait for, now it's time for writting a corotuine:

IEnumerator waiuntilInit()
{
    Initialize();
    yield return new WaitUntil( () => IsInitialized());
    dosomeThing();
}

If you don't like corotutines, you can apply the same idea of waiting with task execution until both m_StoreController and m_StoreExtensionProvider are not null using async/await or doing it in update (with appropriate flags and timers to ensure you do it once) if you wish.

Upvotes: 1

Related Questions