The Unity Ads video ad service provided by Unity helps you engage and monetize your player base. Players need an in-game boost, they watch a video, and you get to reap the monetary rewards. It’s a win-win all around!
In this tutorial, you’ll learn the following as you integrate Unity Ads into your game:
- How to sign up for and add the Unity Ads service.
- How to display simple video ads in your game
- How to design and display reward-linked video ads
- How to leverage Unity Ads features such as filtering and device orientation
You’ll take an existing 2D Space Lander starter project and add in some Unity Ads. By the end, you’ll have a game that demonstrates how to reward players in-game for watching video ads.
Getting Started
Make sure you have the latest version of Unity; this tutorial was written for version 5.3.4. Download the starter project for this tutorial here. Extract and open the IntegratingUnityAdsStarter project in Unity. Don’t worry if you get a warning that the project was opened in an older version of Unity, simply click OK to upgrade.
Don’t worry if you see a script error. This will disappear once your project is set up for the ad service.
The Lander Scene
Open the Lander scene under the Scenes sub-folder. You should see the main game scene, all set up and waiting for you to apply the magic of Unity Ads.
Unity Ads requires that the build platform to be set to either iOS or Android. To follow along with this tutorial, you need to switch the active build platform to one of those two platforms.
From the main menu:
- Select File / Build Settings.
- Select either iOS or Android.
- Click Switch Platform.
The screenshot below shows Android as the build platform.
Switch your game view window to use a portrait aspect ratio, as this game is designed to run in portrait mode.
Setup the Ads Service
Open the Services tab in the editor. You can usually find the tab above the Inspector panel. If not, select Window / Services from the main menu.
Here’s what you should see:
You’ll now link the project to your own Unity organization.
- Click New Link.
- Select your organization name in the drop-down.
- Click Create.
Now to create a Unity Project ID for the game under your organization name.
- Click the toggle on the top right to enable Unity Ads.
- Ensure the slider is in the on position.
- Choose the appropriate Designation for Apps Directed to Children option.
- Click Save Changes.
Expand the Advanced Settings section on the Unity Ads Services tab. Note the two game IDs created for your game. These are used when Unity Ads initializes within the game, and are specific to the mobile platform the game is running on.
The Unity Ads Dashboard
In the Unity Editor Services window, click Go to Dashboard. This will open your web browser and sign you into your Unity Services dashboard. Where you end up depends on how long ago you created your account. You’ll either go to the Unity Ads or the Unity Services dashboard. If you end up on the services dashboard, just click the link for Unity Ads.
You should see your project listed on your Unity Ads Dashboard page.
Initializing Unity Ads
You will be starting things off nice and easy. You’ll check that Unity Ads initialize and display debug information on game start up.
An AdManager.cs script already exists in the starter project. Navigate to the Scripts folder and load it into your code editor.
Add the following debug code to Start()
in AdManager.cs:
Debug.Log("Unity Ads initialized: " + Advertisement.isInitialized); Debug.Log("Unity Ads is supported: " + Advertisement.isSupported); Debug.Log("Unity Ads test mode enabled: " + Advertisement.testMode); |
This lets you check that the Ads service initializes properly. The debug info will display in the console when the game starts.
Save the script and run the game. You should see that the service initializes, there is support for ads and that test mode is enabled.
Adding Video Ads to your Game
What better way to get to the meat of Unity Ads than to tackle some code?
You will now design an ad manager class which will use the Singleton pattern to keep things simple. You will extend the AdManager class that is already in place to let you check that ads are ready. Then it will display the ads and issue rewards for players who finish watching the ad using callback methods.
The Game Over UI
Start the game and fly around until you crash into a rock. You’ll see the game over UI appear with some buttons that offer different ad options. You’ll hook these buttons up to some code in just a bit. For example, notice that the Watch a video ad button does nothing.
Time to make that button display a Unity video ad!
Open AdManager.cs in your code editor and add the following method to the class:
public void ShowStandardVideoAd() { ShowVideoAd(); } |
This method returns void
so that you can attach it to a button action. That button action will call ShowVideoAd()
with no callback and no zone ID to play a standard video ad with the default ad callback handler.
Still working in AdManager.cs, add the following method to the class:
public void ShowVideoAd(Action<ShowResult> adCallBackAction = null, string zone = "") { StartCoroutine(WaitForAdEditor()); if (string.IsNullOrEmpty(zone)) { zone = null; } var options = new ShowOptions(); if (adCallBackAction == null) { options.resultCallback = DefaultAdCallBackHandler; } else { options.resultCallback = adCallBackAction; } if (Advertisement.IsReady(zone)) { Debug.Log("Showing ad for zone: " + zone); Advertisement.Show(zone, options); } else { Debug.LogWarning("Ad was not ready. Zone: " + zone); } } |
StartCoroutine
is a trick to pause the game when running in the editor. It does this by setting the timescale to 0f
. When running on an actual device, Unity Ads will pause the game for you, so this method will do nothing in the editor.
You then check to see if an empty string was passed in as the zone ID. If so, set zone
is set to null
, which causes Unity Ads to display a standard, non-rewarded video ad.
Next a check happens to see if a valid ad callback action was passed in or not. If so, you set the result callback handler to use the callback action you specified. Otherwise a default callback handler assignment takes place.
Finally you check that an ad was preloaded in the background and whether it is ready to play. If ready, the ad launches. The zone and options for callback handling are also passed in here. When the ad is finished playing, was skipped, or fails, a callback method executes depending on the circumstance.
Here’s the final method to add to AdManager.cs:
private void DefaultAdCallBackHandler(ShowResult result) { switch (result) { case ShowResult.Finished: Time.timeScale = 1f; break; case ShowResult.Failed: Time.timeScale = 1f; break; case ShowResult.Skipped: Time.timeScale = 1f; break; } } |
This switch statement is the default ad callback handler. It runs code based on whether the video ad displayed finished, failed, or was skipped.
Wire up the Watch a Video Ad button
Open Lander.cs in your code editor and add the following to the bottom of Start()
:
watchVideoAdBtn.onClick.AddListener(AdManager.instance.ShowStandardVideoAd); |
This will hook up the Watch a standard video ad button to display a standard Unity video ad. Give it a try in the editor and marvel at your simulated video ad that appears! :]
Designing Engaging Ads for Your Game
The key to designing a great ad experience for your game lies in how you integrate Unity Ads. First, ads should be enticing and rewarding for players.
Second, ads should do their best to keep people playing your game. There is no point in displaying a video ad when the player dies, or at the start/end of a level. This is tedious and frustrating to players. It will likely result in them deleting your game.
Ads should integrate into the gameplay experience you’ve crafted for the player. A simple example would be to offer the player consumable in-game items as a reward for watching an ad. Another example would be a second chance after failing (like offering a checkpoint restore). You could offer these rewards in your UI at a resting point or natural break in the gameplay, or as an offer from an in-game character in a dialogue sequence. Remember that forcing players to watch ads is almost certain to lead to uninstalls — videos should always be optional.
Rewarding and Enticing the Player with Rewarded Ads
You now have the ability to show a standard video ad in-game, but with no reward attached. Offering your players a video ad to watch with no reward isn’t going to impress anyone! Nobody is going to watch a video just for the fun of it. Time to change that up and give players an incentive to watch video ads.
The game currently gives the player eight units of fuel to guide their lander down to the landing pad. Too much maneuvering will waste fuel, and players can run out of fuel on the way down. A simple incentive to watch a video ad would be to reward the player with more fuel for their next run after crashing.
Open AdManager.cs in your code editor and add the following method:
public void ShowRewardedFuelVideoAd() { ShowVideoAd(FuelRewardCallBack, "rewardedVideo"); } |
This is a public method that returns void
, which is required when attaching a method to a button.
A custom callback method is passed in that will reward the player. The zone ID is set to “rewardedVideo”. That tells Unity Ads that this video ad will be a rewarded ad.
Also add the following method to AdManager.cs:
private void FuelRewardCallBack(ShowResult showResult) { var fuelBtn = GameObject.Find("MoreFuelRewardAdBtn").GetComponent<Button>(); switch (showResult) { case ShowResult.Finished: Debug.Log("Player finished watching the video ad and is being rewarded with extra fuel."); GameManager.instance.extraFuel = 10f; fuelBtn.transform.GetChild(0).GetComponent<Text>().text = "Fuel added (10 extra)"; fuelBtn.enabled = false; break; case ShowResult.Skipped: Debug.Log("Player skipped watching the video ad, no reward."); fuelBtn.GetComponent<Button>(); fuelBtn.transform.GetChild(0).GetComponent<Text>().text = "No fuel added - you skipped the ad"; fuelBtn.enabled = false; break; case ShowResult.Failed: Debug.Log("video ad failed, no reward."); break; } } |
The code gets a reference to the button in the UI panel. That’s so that the button state and text will be set depending on the result of the video ad.
A switch statement process different actions. In this case, the action is based on whether the video ad gets watched to completion, is skipped, or fails. In the case of completion, extra fuel is added to the GameManager
instance. When the player starts a new game, the extra fuel is added to the player’s fuel supply.
Open Lander.cs and add the following to the bottom of Start()
, just after the other AddListener call you added for the standard video ad button earlier.
fuelRewardBtn.onClick.AddListener(AdManager.instance.ShowRewardedFuelVideoAd); |
This will call ShowRewardedFuelVideoAd()
on the AdManager instance when the player presses the fuel reward button.
Save your code, go back to Unity to try out the results.
Fly around, and either complete a landing, or crash somewhere. You’ll now be able to use the fuel reward button. Since you are in the editor, the test ad will appear. If you look in the console, you will see the debug message “Player finished watching the video ad and is being rewarded with extra fuel”.
If you test this on an actual iOS or Android device, you will see a real video ad play. The same code will be able to determine if you watched the ad to completion or skipped it. If you skipped it, or if the ad failed for some reason, then no fuel reward will be added, and the code for the ShowResult.Skipped
switch statement section runs instead of ShowResult.Finished
.
If you run the app on a device, here is what the test ad experience will look like:
Timing Ad Availability
You can expand the experience even further and add a timed delay to reward items. This can serve to ensure that players don’t get rewards too often. It can also ensure that they don’t request too many video ads. Unity’s ad service does have some limitations on the maximum amount of ads a single user will see every 24 hours.
Timed delay ads can ensure that a player won’t get “failed video” ads after reaching their daily limit. This will prevent players from seeing odd behavior in your game where they try to access a reward.
Wire up the Time-Delayed Present Reward Button
Open AdManager.cs and add the following method:
public bool IsAdWithZoneIdReady(string zoneId) { return Advertisement.IsReady(zoneId); } |
This will check if an ad is ready to display based on the zoneId string you pass to the method.
Open PresentAdReward.cs and add the following method:
private bool IsReady() { if (Time.time > remainingCooldown) { return AdManager.instance.IsAdWithZoneIdReady(zoneId); } return false; } |
This method calls the AdManager’s IsAdWithZoneIdReady()
to see if a video ad is ready. This happens only if your timer has exceeded the remaining cool down time.
Next, add the following to show the video:
private void OpenReward() { AdManager.instance.ShowVideoAd(PresentRewardCallback, zoneId); } |
The method is wired to the Present Reward
button in the UI. When the user clicks the button to watch a video, PresentRewardCallback
will be passed the result.
Now add the code for the callback:
private void PresentRewardCallback(ShowResult result) { switch (result) { case ShowResult.Finished: Debug.Log("Player finished watching the video ad and is being rewarded with extra fuel."); GameManager.instance.extraFuel += rewardAmount; if (coolDown > 0f) { remainingCooldown = Time.time + coolDown; } break; case ShowResult.Skipped: Debug.Log("Player skipped watching the video ad, no reward."); break; case ShowResult.Failed: Debug.Log("video ad failed, no reward."); break; } } |
If the video ad plays to completion, then an amount of fuel gets rewarded to the player for their next run. This is customizable by setting the rewardAmount
float value in the PresentAdReward
script. A check happens to ensure that the cool down value is greater than zero. If it is, then the remaining cool down gets set to the current elapsed game time, plus the cool down value. This has the effect of resetting the count down timer for the reward back to 30 seconds so players will have to wait a further 30 seconds before they can use the reward again.
The skipped and failed cases log information to the console. They don’t reward the player if they skipped the video ad, or the ad failed to play.
To track the elapsed time for the reward cool down, add the following to the Update()
method in PresentAdReward.cs
if (button) { button.interactable = IsReady(); if (button.interactable) { cooldownText.text = "Reward ready! Touch to watch video and open"; } else { cooldownText.text = "Next reward in: " + (int)(remainingCooldown - Time.time) + " seconds"; } } |
The button’s interactable property is set to true
or false
based on whether a video ad is actually ready to play.
If the button is interactable, then the text below the button gets set to "Reward ready!"
. Otherwise, the current remaining time to wait for the reward displays.
Finally, hook OpenPresent()
to the button by adding the following code to the bottom of Start()
in the PresentAdReward.cs script:
button.onClick.AddListener(OpenReward); |
Build and run the game, and crash into a rock to view the game over screen. You should now see a shiny reward present available for you to click on!
Tap or click on the present icon to view the video ad. Then receive your staggeringly large supply of 20 reward fuel! After closing the ad, you’ll notice that the reward won’t be available for 30 seconds and the count down timer displays instead.
Remove your Test Button
Well done on making it this far! :]
Time for a little cleanup. You’ll now remove the button that lets players watch a video ad with no reward attached. Hooking this button up to the Unity Ads API was a useful learning exercise on using Unity Ads. But really, nobody will want to watch an ad without a reward.
Go to the Lander scene and remove the button as follows:
- In the Hierachy: expand the Canvas GameObject.
- Expand the GameOverPanel GameObject.
- Expand the ButtonsPanel.
- Right-Click the WatchVideoAdBtn GameObject.
- Click Delete.
Open the Lander.cs script in your code editor, and remove the private field variable called watchVideoAdBtn from the top of the class.
Remove the following line from Start()
:
watchVideoAdBtn = GameObject.Find("WatchVideoAdBtn").GetComponent<Button>(); |
Then a little further down in the method find and remove this line:
watchVideoAdBtn.onClick.AddListener(AdManager.instance.ShowStandardVideoAd); |
Save the Lander.cs script, go back to the Unity Editor, and run the game. After crashing (or landing), you’ll notice that the old button is now gone. You simply have the two buttons providing fuel rewards in return for watching video ads.
Here is what the timed ad reward experience looks like on an actual device:
Switching Off Test Mode for Game Release
The last thing to do before releasing your game to the Apple or Android stores is to switch off ad test mode. There is a way to force test mode off through the Unity Ads Admin panel if you forget to disable test mode before releasing your game, but it’s best to do this before submitting your app.
Click the Services tab in the Unity Editor and click on Ads. Un-check Test Mode.
That is it! If you run your game on an actual device at this point, you will get live Unity Ads coming through.
Changing the Orientation of Your Video Ads
If you release your game as a portrait orientation app, video ads may play in landscape mode on the device. That requires players to tilt their device to the side to view the videos — that’s a little awkward. In that case, follow these steps to change the ads to match the orientation.
- Login to your Ads portal.
- Select your Unity Ads project.
- Click on the link for the App Store you are targeting.
- Select the Settings tab.
- Toggle Video Orientation to on.
- Click Save.
Don’t be that developer who forces players to rotate their devices the other way around to view ads! :]
Filtering Ads
In some cases you may wish to exclude certain ad categories from displaying to your players. Filtering out ads is a simple task thanks to the Unity Ads admin portal. Here is how you can define a set of filtered out categories:
- Login to the Unity Ads portal.
- Select your project.
- Select a platform store<./li>
- Click the Ad Filtering tab.
- Select the categories you wish to exclude.
- Click Save.
Show Me the Money!
To view revenue and reports, login to your Unity Ads portal and click on your project name.
Click the Statistics tab which will show you your project overview. This table shows you revenue, eCPM, and Ad Starts for three intervals: Last 24 hours, last 7 days, and the last 30 days.
You can also export your Unity Ads raw data in CSV format on this page. Just below the Project Overview section is the area you can use to generate reports in CSV format.
To start receiving payments for your Unity Ads revenue, you’ll need to have earned at least $100.00 in ad revenue earnings. You’ll also need to fill out a few details on the Unity Ads dashboard, and generate an invoice to send to Unity.
Go to the main dashboard for Unity Ads, and click the Invoicing tab.
You’ll need to provide some details here such as your VAT ID (if you have one), and address details. Fill these out, and click Save.
Once you have reached at least $100.00 in earnings you can generate an invoice addressed to Unity Ads.
The very first time you invoice Unity Ads, you’ll also need to fill out a Wire Transfer Information form. This form is located here.
This does require a little bit of work up front, but once you’ve done it, the next time around is much easier! :]
Where to Go From here?
You can download the final project here. Before you can run it, you’ll need to re-link it to your own Unity Ads account.
If you have more questions about Unity Ads, there is an excellent FAQ website you can visit: https://unityads.unity3d.com/help/faq/monetization. This answers lots of common (and not so common!) questions on the platform.
There’s also some great Unity resources below on monetization and video ads:
If you have questions or comments on this tutorial, please join the forum discussion below!
The post Integrating Unity Ads into Your Game appeared first on Ray Wenderlich.