[Closed] Using Codeless API to trigger purchase event

I’m using the codeless API to make my buttons, but I need to instantiate the buttons via script. So far, I am able to get it mostly working by making the button and adding a IAPButton.cs script to it, then disabling the button. I then set up the type of button, set it’s productID etc. via my own script. Finally, I enable the button.

What I can’t seem to do is to add a listener to the new button. This post seemed the most helpful, adding a delegate to the button. Here is the relevant code:

IAPButton iapButton = btn.gameObject.AddComponent<IAPButton>() as IAPButton;
iapButton.enabled = false;
iapButton.productId = btn.m_item.m_itemID;
iapButton.priceText = btn.m_priceLabel;
iapButton.titleText = btn.m_descriptionLabel;
iapButton.consumePurchase = false;
iapButton.buttonType = IAPButton.ButtonType.Purchase;

iapButton.onPurchaseComplete.AddListener(delegate { btn.ActivateNewPurchase(); });
iapButton.enabled = true;
}

The code compiles, but when running I get a “NullReferenceException: Object reference not set to an instance of an object” error on line 10.

What am I doing wrong?

My first issue was an obvious one – the ActivateNewPurchase() function needed to accept the Product object. So it should be ActivateNewPurchase(Product p) and not a function with no parameters.

Then, I need to put the IAPButton script on my button while it’s a prefab. I can then alter the product.id and after making the UpdateText() function public, I call it to update everything. Works OK, but still not sure why I can’t just create it at runtime.

You should probably consider not using Codeless IAP for what you are doing, but rather use scripting as described in this article as it will give you additional flexibility Unity IAP - Unity Learn

Yes, I have gradually realized that using Codeless is creating problems for me since I am doing several things via code. I did go through that tutorial and I think the IAPDemo is also going to help me figure this out.