Categories
Game Creation Mastering Development

Unity ads issue – null reference error

I’m trying to add unity ads to my game. In my game there are three panels – startgame, ingame and gameover. Once the game starts, only the startgame panel is active and once you tap on the screen, the ingame panel gets actived and startgame panel is deactivated. In the ingame panel I have added a button to show ads (once an ad is ready) so that after watching the ad, user can receive 100 additional points. Here is my admanager script:

string GooglePlay_ID = "123456";
bool test_mode = true;
string myPlacementId = "rewardedVideo";    

public Button inGameAdBtn;    

void Start()
{       
  inGameAdBtn = GetComponent<Button>();
  inGameAdBtn.interactable = Advertisement.IsReady(myPlacementId);
  if (inGameAdBtn) inGameAdBtn.onClick.AddListener(ShowRewardedVideo);
  
  Advertisement.AddListener(this);        
  Advertisement.Initialize(GooglePlay_ID, test_mode);
}

public void ShowRewardedVideo()
{        
    Advertisement.Show(myPlacementId);
}

public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{

    if (showResult == ShowResult.Finished)
    {
        GameManager.instance.GetPoints();      
    }

else if (showResult == ShowResult.Skipped)
    {

    }

    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)
    {
        inGameAdBtn.interactable = true;
    }
}

public void OnUnityAdsDidError(string message)
{
    // Log the error.
}

public void OnUnityAdsDidStart(string placementId)
{
    // Optional actions to take when the end-users triggers an ad.
}

When I hit play, I get an error in the console saying – NullReferenceException: Object reference not set to an instance of an object. When I click on it, it takes to this line of code "inGameAdBtn.interactable = Advertisement.IsReady(myPlacementId);".

I believe this is because once the game starts, the ingame panel is inactive and the admanager script is looking for the inGameAdBtn (which is in the ingame panel). Is there any way to resolve this issue?

Leave a Reply

Your email address will not be published. Required fields are marked *