Objective: Set up the coding side of rewarding ads for your game!
In the previous tutorial we set up all the “physical” assets for ads for our mobile game. In this tutorial we are going to focus on setting up the code to allow these ads to work.
Let’s begin with opening the ads initializer script we created in the last tutorial. We need to add the I Unity Ads Initialization Listener interface, and to do this we need to add the advertisements library.
right click and select Quick actions and Refactoring, then implement interface.
This will automatically add the missing methods to your script. We need to add strings for android game ID/IOS game ID, a bool for test mode, and a string for game ID.
We need an method to handle initializing your ads. This method will set the game ID to either IOS or android. We will call this method using an awake method.
The method On Initialization Complete method we want to load an ad when it’s called.
We are now done with this script now move on to the ads manager script. we need to add the advertisement and UI libraries.
We need to add I Unity Ads Show Listener / I Unity Ads Load Listener interfaces. This will generate 6 methods.
We need a button variable to represent the button we created in the shop, a string for our ad ID, and this being a manager we can go ahead and turn this into a singleton.
we need to make that Load Ad method we are trying to call on the initializer script.
we need a method that check for if the placement ID equals the ad ID then the button, we created becomes interactable and create an on click event that adds listener.
The On Unity Ads Failed To Load method we need a log to let us know it failed.
The On Unity Ads Show Complete method we check if the ad ID matches our ad ID and if the ad is complete, load another ad. We also can set up a switch statement to check if the complete state is skipped/completed/or unknown. If it is skipped or unknown, then we will do nothing. If complete, then we need to add 100G to the player and the UI.
The remaining methods don’t need to do anything.
That finishes this script too. Now head to the editor and select the ads manager. In the inspector we need to assign the ads button from the shop keeper and the ad ID. The ad ID is located in the dashboard.
While in the dashboard we need to locate the game ID’s.
Now test it out and you game should now have working ads. It wont play the ad in the editor however if you create an APK and port it to your phone you will see the ad play completely.
Now you know how to implement ads into your game! I’ll see you in the next tutorial!