- Home /
Help implementing unity ads
I'm trying to implement unity ads for my first ever game. It's nearly finished but I want to monetize it before putting it on Google Play. The problem is I'm getting errors in my code and can't find anything online and these functions are completely new to me. I have also added the rewardedVideo placement on my dashboard to my game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
public class Ads : MonoBehaviour
{
string gameId = "3368495";
myPlacementId = "rewardedVideo"; //Error here: The name placement id does not exist in the current context
bool testMode = true;
// Initialize the Ads listener and service:
void Start()
{
Advertisement.AddListener(this); //Error here: Advertisment does not contain a definition AddListener
Advertisement.Initialize(gameId, testMode);
}
// Implement IUnityAdsListener interface methods:
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
// Define conditional logic for each ad completion status:
if (showResult == ShowResult.Finished)
{
// Reward the user for watching the ad to completion.
}
else if (showResult == ShowResult.Skipped)
{
// Do not reward the user for skipping the ad.
}
else if (showResult == ShowResult.Failed)
{
Debug.LogWarning("The ad did not finish due to an error");
}
}
public void OnUnityAdsReady(string placementId)
{
// If the ready Placement is rewarded, show the ad:
if (placementId == myPlacementId) //Error here: The name myPlacementId does not exist in the current context
{
Advertisement.Show(myPlacementId); //Error here: The name myPlacementId does not exist in the current context
}
}
public void OnUnityAdsDidError(string message)
{
// Log the error
}
public void OnUnityAdsDidStart(string placementId)
{
// Optional actions to take when the end-users triggers an ad.
}
}
Anything helps and I should also note that I have plans for IAP as well. Thanks!
This is where I got my code from I used the rewarded video ads section
Answer by PruneDealer · Nov 20, 2019 at 04:48 AM
Nevermind guys I think I got it. With a much simpler code as well! using UnityEngine.Advertisements; using UnityEngine.UI;
public class Ads : MonoBehaviour
{
public void ShowRewardedAd()
{
if (Advertisement.IsReady("rewardedVideo"))
{
var options = new ShowOptions { resultCallback = HandleShowResult };
Advertisement.Show("rewardedVideo", options);
}
}
private void HandleShowResult(ShowResult result)
{
switch (result)
{
case ShowResult.Finished:
Debug.Log("Finished");
PlayerPrefs.SetInt("Balance", PlayerPrefs.GetInt("Balance") + 10);
break;
case ShowResult.Skipped:
Debug.Log("Skipped");
break;
case ShowResult.Failed:
Debug.Log("Failed");
break;
}
}
}
Let me know if there's something I'm missing but everything seems to work okay so I'm not to worried.