using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using GoogleMobileAds.Api;
public class AdManager : MonoBehaviour {
/// <summary>
/// GoogleAd
/// </summary>
private BannerView bannerView;
/// <summary>
/// MyAd
/// </summary>
private string url = "http://www.xxxxxxx.cn/test.php";
public Image image;
private string link_url;
// Use this for initialization
void Start()
{
///GoogleAd
#if UNITY_ANDROID
string appId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx";
#elif UNITY_IPHONE
string appId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx";
#else
string appId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx";
#endif
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(appId);
this.RequestBanner();
///MyAd
LoadPHP();
}
private void RequestBanner()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxxx/xxxxxxxxxx";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx";
#else
string adUnitId = "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx";
#endif
// Create a 320x50 banner at the top of the screen.
bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
bannerView.LoadAd(request);
}
private void LoadPHP()
{
StartCoroutine(GetText());
}
IEnumerator GetText()
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.Send();
if (www.isNetworkError)
{
Debug.Log(www.error);
}
else
{
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
string data = System.Text.Encoding.Default.GetString(results);
AdBean adbean = JsonUtility.FromJson<AdBean>(data);
Debug.Log(adbean.id);
Debug.Log(adbean.image_path);
Debug.Log(adbean.link_path);
link_url = adbean.link_path;
LoadByWWW(adbean.image_path);
}
}
}
private void LoadByWWW(string iamge_url)
{
StartCoroutine(Load(iamge_url));
}
private IEnumerator Load(string iamge_url)
{
double startTime = (double)Time.time;
WWW www = new WWW(iamge_url);//只能放URL
//只能放URL 这里可以换做网络的URL
yield return www;
if (www != null && string.IsNullOrEmpty(www.error))
{
Texture2D texture = www.texture;
//创建 Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 320, 50), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
}
}
public void click()
{
print("点击事件..." + link_url);
Application.OpenURL(link_url);
}
}