I am looking to integrate admob interstitial in Unity, i did it for banner but unable to find final solution for interstitial, any help would be appreciated.
I tied following links but it didn't work for Interstitial
https://github.com/googleads/googleads-mobile-plugins
Please do not suggest any paid plugin as Prime31 etc.
You can download the unity package from the google developer page here
If the free plugin doesn't suit your needs, you'll have to write your own native plugin or purchase on on the Asset Store. However, that plugin's README says it supports interstitials. Try following the instructions in the readme. If you already tried that and it didn't work, it would help if you tell us exactly what went wrong.
Taken from that readme:
Here is the minimal banner code to create an interstitial.
using GoogleMobileAds.Api;
...
// Initialize an InterstitialAd.
InterstitialAd interstitial = new InterstitialAd("MY_AD_UNIT_ID");
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the interstitial with the request.
interstitial.LoadAd(request);
Unlike banners, interstitials need to be explicitly shown. At an appropriate stopping point in your app, check that the interstitail is ready before showing it:
if (interstitial.IsLoaded()) {
interstitial.Show();
}
There's a done Unity Package for AdMob which I used in my android game, you can find it in here: http://forum.unity3d.com/threads/admob-unity-package-that-work-with-unity-3-2-above.173292
Make sure to go through the whole thread because it needs a bit of tuning to get it working perfectly with newer unity versions.
Little help about the app publisher id - look for page7 on the thread.
try https://github.com/unity-plugins/Unity-Admob.
I have success with this one.
and code is much more easy.
using UnityEngine;
using System.Collections;
using admob;
public class admobdemo : MonoBehaviour {
// Use this for initialization
void Start () {
Admob.Instance().bannerEventHandler += onBannerEvent;
Admob.Instance().interstitialEventHandler += onInterstitialEvent;
}
// Update is called once per frame
void Update () {
}
void OnGUI(){
if (GUI.Button (new Rect (0, 0, 100, 60), "initadmob")) {
Admob ad = Admob.Instance();
#if UNITY_IOS
ad.initAdmob("ca-app-pub-27960454450664210/xxxxxxxxx", "ca-app-pub-279343530664210/xxxxxxxxxxx");
#else
ad.initAdmob("ca-app-pub-27960454450664210/xxxxxxxxx", "ca-app-pub-279343530664210/xxxxxxxxxxx");
#endif
// ad.setTesting(true);
}
if (GUI.Button(new Rect(120, 0, 100, 60), "showfull"))
{
Admob ad = Admob.Instance();
if (ad.isInterstitialReady())
{
ad.showInterstitial();
}
else
{
ad.loadInterstitial();
}
}
if (GUI.Button(new Rect(240, 100, 100, 60), "showbanner"))
{
Admob.Instance().showBannerRelative(AdSize.Banner, AdPosition.BOTTOM_CENTER, 0);
}
if (GUI.Button(new Rect(240, 200, 100, 60), "showbannerABS"))
{
Admob.Instance().showBannerAbsolute(AdSize.Banner, 0, 30);
}
if (GUI.Button(new Rect(240, 300, 100, 60), "hidebanner"))
{
Admob.Instance().removeBanner();
}
}
void onInterstitialEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobEvent---" + eventName + " " + msg);
if (eventName == AdmobEvent.onAdLoaded)
{
Admob.Instance().showInterstitial();
}
}
void onBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobBannerEvent---" + eventName + " " + msg);
}
}
Here you go. Google's official Unity Plugin and they have code sample for Banner and Interstitial Ads.
Related
I'm trying to use a cloud TTS within my Unity game.
With the newer versions (I am using 2019.1), they have deprecated WWW in favour of UnityWebRequest(s) within the API.
I have tried the Unity Documentation, but that didn't work for me.
I have also tried other threads and they use WWW which is deprecated for my Unity version.
void Start()
{
StartCoroutine(PlayTTS());
}
IEnumerator PlayTTS()
{
using (UnityWebRequestMultimedia wr = new UnityWebRequestMultimedia.GetAudioClip(
"https://example.com/tts?text=Sample%20Text&voice=Male",
AudioType.OGGVORBIS)
)
{
yield return wr.Send();
if (wr.isNetworkError)
{
Debug.LogWarning(wr.error);
}
else
{
//AudioClip ttsClip = DownloadHandlerAudioClip.GetContent(wr);
}
}
}
The URL in a browser (I used Firefox) successfully loaded the audio clip allowing me to play it.
What I want it to do is play the TTS when something happens in the game, it has been done within the "void Start" for testing purposes.
Where am I going wrong?
Thanks in advance
Josh
UnityWebRequestMultimedia.GetAudioClip automatically adds a default DownloadHandlerAudioClip which has a property streamAudio.
Set this to true and add a check for UnityWebRequest.downloadedBytes in order to delay the playback before starting.
Something like
public AudioSource source;
IEnumerator PlayTTS()
{
using (var wr = new UnityWebRequestMultimedia.GetAudioClip(
"https://example.com/tts?text=Sample%20Text&voice=Male",
AudioType.OGGVORBIS)
)
{
((DownloadHandlerAudioClip)wr.downloadHandler).streamAudio = true;
wr.Send();
while(!wr.isNetworkError && wr.downloadedBytes <= someThreshold)
{
yield return null;
}
if (wr.isNetworkError)
{
Debug.LogWarning(wr.error);
}
else
{
// Here I'm not sure if you would use
source.PlayOneShot(DownloadHandlerAudioClip.GetContent(wr));
// or rather
source.PlayOneShot((DownloadHandlerAudioClip)wr.downloadHandler).audioClip);
}
}
}
Typed on smartphone so no warranty but I hope you get the idea
I have 2 issues when using PhotoCapture on the Hololens 2, which are probably connected. They did not occur on the Hololens 1.
The only obtainable resolution is 3904x2196
Getting the CameraToWorldMatrix always fails
As can be seen in the docs, this resolution has no framerate associated with it.
My presumption is that the CameraToWorldMatrix is only obtainable for camera profiles with a lower resolution.
How can i change the resolution and get the matrix within Unity?
Minimal Reproducible Example
I am using Unity 2019.2.19f1 and Visual Studio 2019 Community (16.4.5)
Create a new Unity Project following the steps here, except using IL2CPP as the scripting backend instead of .NET
In Player Settings: Capabilities enable InternetClient, InternetClientServer, PrivateNetworkClientServer, Webcam, Microphone and SpatialPerception, in Player Settings: Supported Device Families select Holographic
Create a new empty gameobject and add the following script:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Windows.WebCam;
public class PhotoCaptureController : MonoBehaviour
{
PhotoCapture photoCaptureObject = null;
bool isRunning = false;
void Start()
{
StartCoroutine(StartCameraCapture());
}
private IEnumerator StartCameraCapture()
{
if (!Application.HasUserAuthorization(UserAuthorization.WebCam))
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
}
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
Debug.Log("Creating PhotoCapture");
PhotoCapture.CreateAsync(false, OnPhotoCaptureCreated);
}
else
{
Debug.Log("Webcam Permission not granted");
}
}
private void Update()
{
if (isRunning)
{
photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
}
}
void OnPhotoCaptureCreated(PhotoCapture captureObject)
{
photoCaptureObject = captureObject;
IEnumerable<Resolution> availableResolutions = PhotoCapture.SupportedResolutions;
foreach (var res in availableResolutions)
{
Debug.Log("PhotoCapture Resolution: " + res.width + "x" + res.height);
}
Resolution cameraResolution = availableResolutions.OrderByDescending((res) => res.width * res.height).First();
CameraParameters c = new CameraParameters();
c.hologramOpacity = 0.0f;
c.cameraResolutionWidth = cameraResolution.width;
c.cameraResolutionHeight = cameraResolution.height;
c.pixelFormat = CapturePixelFormat.BGRA32;
captureObject.StartPhotoModeAsync(c, OnPhotoModeStarted);
}
private void OnPhotoModeStarted(PhotoCapture.PhotoCaptureResult result)
{
if (result.success)
{
isRunning = true;
photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
}
}
void OnCapturedPhotoToMemory(PhotoCapture.PhotoCaptureResult result, PhotoCaptureFrame frame)
{
if (result.success)
{
if (frame.TryGetCameraToWorldMatrix(out Matrix4x4 cameraToWorldMatrix))
{
Debug.Log("Successfully obtained CameraToWorldMatrix: " + cameraToWorldMatrix.ToString());
}
else
{
Debug.Log("Failed to obtain CameraToWorldMatrix");
}
}
frame.Dispose();
}
}
Change Build Settings:
Build, open VS solution, set build target to ARM64, Debug and deploy to Device
This CameraCapture plugin may work for you. It's a native plugin for Unity. The readme.txt contains information on building it. Basically, you need to build the native plugin variants before trying to open up the Unity sample. If you haven’t built C++/WinRT components, you may need to go through the setup steps here. The SpatialCameraTracker.cs file shows how to receive the camera matrices.
There is minimal support on this but all the code is in the repo
Question asked just to give solution :)
Main idea is to recognize QR-code on Unity without ANY additional action like tapping on the screen or sth like this.
(For me it's not necessary that "vuforia free" have watermark, so here is my solution)
(Also Vuforia works with camera much faster and no need to realize manually autofocus)
Continious QR code recognition using Vuforia as webcam source and ZXing Library as QR recognizer
using UnityEngine;
using Vuforia;
using ZXing;
public class QRCodeReader : MonoBehaviour {
private bool _isFrameFormatSet;
IBarcodeReader _barcodeReader = new BarcodeReader();
void Start () {
InvokeRepeating("Autofocus", 2f, 2f);
}
void Autofocus () {
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_TRIGGERAUTO);
RegognizeQR();
}
private Vuforia.Image GetCurrFrame()
{
return CameraDevice.Instance.GetCameraImage(Vuforia.Image.PIXEL_FORMAT.GRAYSCALE);
}
void RegognizeQR()
{
if (!_isFrameFormatSet == _isFrameFormatSet)
{
_isFrameFormatSet = CameraDevice.Instance.SetFrameFormat(Vuforia.Image.PIXEL_FORMAT.GRAYSCALE, true);
}
var currFrame = GetCurrFrame();
if (currFrame == null)
{
Debug.Log("Camera image capture failure;");
}
else
{
var imgSource = new RGBLuminanceSource(currFrame.Pixels, currFrame.BufferWidth, currFrame.BufferHeight, true);
var result = _barcodeReader.Decode(imgSource);
if (result != null)
{
Debug.Log("RECOGNIZED: " + result.Text);
}
}
}
}
Its possible to realize also without Vuforia, ofc. Unity provides the possibility to get a camera and show it’s input on a webcamtexture. It's possible to find more documentation here.
ZXing lib you can find here, or build it by your own hands using sourse code located on github.
Both libs is cross-platform, so must be no issues on different devices.
I just published a game I made using Unity3D to Google Play. When I made tests before putting the game on the strore - I was able to see test ads. Now, that my game is on the store - I can't see any banner ads.
This is my code for showing adds, what's wrong here?
BannerView BV;
string adUnitId = "ca-app-pub-123456789/987654321";
void Start()
{
BV = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
RB(); //Request Banner
SB(); //Show Banner
}
private AdRequest createAdRequest()
{
return new AdRequest.Builder()
.AddKeyword("Game")
.SetGender(Gender.Male)
.SetBirthday(new DateTime(1988, 9, 4))
.TagForChildDirectedTreatment(true)
.Build();
}
void RB()
{
BV.LoadAd(createAdRequest());
}
internal void SB()
{
BV.Show();
}
Look at your log. It will tell you if an ad request has been made and what the result was.
If there are no ads to display, it will test you.
I suspect that is what is happening.
I'm having a problem when using the Facebook Unity API, calling the FB.Feed() method. It winds up giving this error:
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUILayoutUtility.DoGetRect (UnityEngine.GUIContent content,
UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at
C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUILayoutUtility.cs:264)
which is immediately followed by:
ArgumentException: Getting control 1's position in a group with only 1 controls
when doing Repaint
I know the second error is usually caused in Unity by GUI elements changing between GUI event calls, etc. In my case, however, I'm not doing anything within OnGUI at all. In fact, because of tearing my hair out trying to figure out what the problem is, I created a totally new project - 1 scene with basic buttons to login, and then "brag" using the FB.Feed. I've written it the exact way that their documents show, and I get the exact same error.
I'm hoping maybe someone might be able to shed some light on what I'm missing or doing wrong.
Here is complete code in my simple barebones scene that also causes this error:
void Start()
{
FB.Init(OnInitComplete, OnHideUnity);
}
void OnInitComplete()
{
Debug.Log("FB Initialized");
}
void OnHideUnity(bool isGameShown)
{
Debug.Log("OnHideUnity");
if (!isGameShown)
Time.timeScale = 0;
else
Time.timeScale = 1;
}
void Update()
{
}
void OnGUI()
{
if (!FB.IsLoggedIn)
{
if (GUI.Button(new Rect(10, 10, 100, 30), "Login"))
FBLogin();
}
else
{
if (GUI.Button(new Rect(10, 50, 100, 30), "Brag"))
{
Brag();
}
}
}
void Brag()
{
FB.Feed(
linkCaption: "This is testing the testapp FEED",
picture: "http://myapp.com/myapplogo.jpg",
linkName: "Foo Link",
link: "http://apps.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? FB.UserId : "guest")
);
}
void FBLogin()
{
FB.Login("email, publish_actions", OnLoggedIn);
}
void OnLoggedIn(FBResult result)
{
if (FB.IsLoggedIn)
Debug.Log("Logged in successfully");
}
My Facebook API is version 140220, and my Unity is 4.3.4
I'll do my best to answer any other questions for info I've missed
I've also tried using the FB API version 131022, and have the same results.
This error also happens with the FriendSmash example and as well with the InteractiveConsole example scene provided with the plugin.
I should also point out that the Window does open for the post, and loads the image, link, etc. The exception prevents anything else from working however
Additional Info: I've found that when the app is ran on an actual android device, the feed post works with no problem. It only appears to have this error within the Unity editor. I have another issue with test users logging in on the android device - they can't if the device has the Facebook app itself installed, but that issue probably warrants a separate question
I think it's just not getting all of the resources it's asking for. The docs say not to worry about it, the editor can only do so much. I get the one below. Unfortunately though, mine is not working on the device, but if yours is, I wouldn't worry about it too much.
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.GUILayoutUtility.DoGetRect (UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUILayoutUtility.cs:264)
UnityEngine.GUILayoutUtility.GetRect (UnityEngine.GUIContent content, UnityEngine.GUIStyle style) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUILayoutUtility.cs:257)
Facebook.FbSkinnedDialog.TwoButtonBar (System.String label, System.String cancelLabel)
Facebook.FeedDialog.UpdateDialog (Int32 windowID)
Facebook.FbSkinnedDialog.GeneralUpdateDialog (Int32 windowId)
UnityEngine.GUI.CallWindowDelegate (UnityEngine.WindowFunction func, Int32 id, UnityEngine.GUISkin _skin, Int32 forceRect, Single width, Single height, UnityEngine.GUIStyle style) (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/GUI.cs:1395)