Home > Software engineering >  Unity3D invalid token error on official code from documentation
Unity3D invalid token error on official code from documentation

Time:12-15

i was trying to set up simple ad system in my game in unity but the rewarded ads script from unity documentation is giving me invalid token error and i have no idea why

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;

public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
    public string _adUnitId = null;
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif

Assets\Scripts\RewardedAdsButton.cs(14,13): error CS1519: Invalid token '=' in class, struct, or interface member declaration

Assets\Scripts\RewardedAdsButton.cs(14,31): error CS1519: Invalid token ';' in class, struct, or interface member declaration

CodePudding user response:

The documentation is extremely misleading in this case!

You can't just reassign a field on class level. Especially not using other non constant fields! You can't have this outside of any method.


This is probably supposed to happen in a method like e.g. in Awake

public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOSAdUnitId = "Rewarded_iOS";

    [NonSerialized] public string _adUnitId = null;

    private void Awake ()
    {
#if UNITY_IOS
        _adUnitId = _iOSAdUnitId;
#elif UNITY_ANDROID
        _adUnitId = _androidAdUnitId;
#endif
    }

    ...
}

Or alternatively I would actually rather simply use a property like e.g.

public class RewardedAdsButton : MonoBehaviour, IUnityAdsLoadListener, IUnityAdsShowListener
{
    [SerializeField] Button _showAdButton;
    [SerializeField] string _androidAdUnitId = "Rewarded_Android";
    [SerializeField] string _iOSAdUnitId = "Rewarded_iOS";

    public string _adUnitId
    {
        get
        {
#if UNITY_IOS
            return _iOSAdUnitId;
#elif UNITY_ANDROID
            return _androidAdUnitId;
#else
            return null;
#endif
        }
    }
  • Related