- Home /
Is this a valid way to add a parameter to a class?
I'm using a reference book to implement Unity Ads in a game. I'm following the code verbatim but I'm getting a compile error that seems to be caused by a parameter that's undefined. However, I've checked the book's errata and there's no mention of an error for the page containing this code. Also the author states "We also added in a new parameter with a default value," so it seems he intended the very line of code that Visual Studio is flagging, and since I'm still learning the basics of C#, I'm complete baffled as whether the flagged line is the problem or if the problem is somewhere else.
There are two scripts that the author uses in this case. One is for an Ad Controller, and the other is for a Menu Controller. Visual Studio is specifically flagging the line of code within the MainMenuBehaviour script if (UnityAdController.showAds)
The error message is 'UnityAdController' does not contain a definition for 'showAds'
This does seem to be true as showAds isn't defined in the UnityAdController script, but again, the author specifically states "We also added in a new parameter with a default value," and so it seems that he did intend that specific line of code. Since I'm still a beginner, I haven't been able to figure out whether the problem really is that specific line of code or if there's an error elsewhere or if the problem is both that line of code and elsewhere. So I'm hoping I can get help identifying and correcting the error.
Thanks!
Ad Controller script:
#if UNITY_ADS//Can only compile ad code on supported platforms
using UnityEngine.Advertisements;//Advertisement class
#endif
public class UnityAdController : MonoBehaviour
{
public static void ShowAd()
{
#if UNITY_ADS
if (Advertisement.IsReady())
{
Advertisement.Show();
}
#endif
}
}
Menu Controller:
(note only the portion between #if and #endif are new code in terms of presentation within the book, which is why it would seem to be the problem as that is what Visual Studio is flagging, and the compile error started after the addition of those lines).
using UnityEngine;
using UnityEngine.SceneManagement; //Load Scene
public class MainMenuBehaviour : MonoBehaviour
{
///<summary>
///Will load a new scene upon being called
/// </summary>
/// <param name="levelName">The name of the level we want
/// to go to</param>
public void LoadLevel(string levelName)
{
SceneManager.LoadScene(levelName);
#if UNITY_ADS
if (UnityAdController.showAds)
{
//Show an ad
UnityAdController.ShowAd();
}
#endif
}
}
public class UnityAdController : $$anonymous$$onoBehaviour
{
public static bool showAds = true;
public static void ShowAd()
{
#if UNITY_ADS
if (Advertisement.IsReady())
{
Advertisement.Show();
}
#endif
}
}
Your answer
