Unity ads, Video always fails to show - c#

I have this code and after I execute it with a button console every time that prints out that video, it fails. Maybe I just don't know how to enable ads in Unity. I have test mode enabled. This is my code. :
FIXED i just needed to replace this line
public string placementId = "rewardedVideo";
with this:
Advertisement.Show(placementId, options);
private string gameId = "1523603";
void Start(){
Advertisement.Initialize (gameId);
}
public void ShowAd (){
var options = new ShowOptions();
options.resultCallback = HandleShowResult;
Debug.Log (Advertisement.IsReady ("rewardedVideo"));
Advertisement.Show(gameId, options);
}
void HandleShowResult (ShowResult result){
if(result == ShowResult.Finished) {
Debug.Log("Video completed - Offer a reward to the player");
OnemoreTry ();
}else if(result == ShowResult.Skipped) {
Debug.LogWarning("Video was skipped - Do NOT reward the player");
}else if(result == ShowResult.Failed) {
Debug.LogError("Video failed to show");
}
}

Related

itineration problem with function after resume app

this probably is a noob question, but I can't figure out how resolve it.
Im opening/resuming my android app from a notification (intent data).
the app is opening fine from the intent.
the problem is if send the app to the background again after opening from the intent and later I resume again, the coroutine executes again every time I resume, because keeps getting the data from the "old" intent.
*is there some way of clear the intent data? (without close the app)
im trying something like: AndroidJavaObject saveIntent = curActivity.Call<AndroidJavaObject>("setData");
to replace the intent data so the next itineration dont get te correct values
*Im thinking to limit to 1, the times what the coroutine can be executed, but not is a "clean"solution.
can someone give me some guidance?.
this is my code so far:
void OnApplicationPause(bool appPaused)
{
if (!isOnAndroid || Application.isEditor) { return; }
if (!appPaused)
{
//Returning to Application
Debug.Log("Application Resumed");
StartCoroutine(LoadSceneFromFCM());
}
else
{
//Leaving Application
Debug.Log("Application Paused");
}
}
IEnumerator LoadSceneFromFCM()
{
AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject curActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject curIntent = curActivity.Call<AndroidJavaObject>("getIntent");
string sceneToLoad = curIntent.Call<string>("getStringExtra", "sceneToOpen");
//string extraInfo = curIntent.Call<string>("getStringExtra", "extraInfo"); use this for do some extra stuff
Scene curScene = SceneManager.GetActiveScene();
if (!string.IsNullOrEmpty(sceneToLoad) && sceneToLoad != curScene.name)
{
// If the current scene is different than the intended scene to load,
// load the intended scene. This is to avoid reloading an already acive
// scene.
Debug.Log("Loading Scene: " + sceneToLoad);
Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Large);
Handheld.StartActivityIndicator();
yield return new WaitForSeconds(0f);
SceneManager.LoadScene(sceneToLoad);
}
}
this is working for me now:
void Awake()
{
DontDestroyOnLoad(gameObject);
}
void OnApplicationPause(bool appPaused)
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject intent = currentActivity.Call<AndroidJavaObject>("getIntent");
Scene curScene = SceneManager.GetActiveScene();
string sceneToLoad = intent.Call<string>("getStringExtra", "sceneToOpen");
if (sceneToLoad != null && sceneToLoad.Trim().Length > 0 && sceneToLoad != curScene.name)
{
Debug.Log("Load the Video Scene");
SceneManager.LoadScene(sceneToLoad);
//redirectToAppropriateScreen(intent, onClickScreen);
}
intent.Call("removeExtra", "sceneToOpen"); //this remove the data from the intent, so the function cant be completed after resume again.
Debug.Log("Extra data removed");
}

Tiles not following input in a branching board game path

I'm making a board game in Unity with multiple branching paths where the players can decide which one to follow. (Think the Mario Part game board) But the player input on which path to follow isn't working.
So I have a script that has the tokens follow a set path and (Linked List for the path) with a for loop to have the tokens move their allocated amount. Within the loop, I have an If statement that checks how many paths the tile has and if there are more than one if runs a separate script that pauses the game and offers a menu prompt for the players to pick one path or the other.
I've tried tossing in a few contitions for continuing the game within the loop but they either ignore the player input, are an input behind or just break the code.
`for (int i = 0; i < spacesToMove; i++)
{
if (final_Waypoint == null)
{
final_Waypoint = Starting_Waypoint;
}
else
{
if (final_Waypoint.Next_Waypoint == null || final_Waypoint.Next_Waypoint.Length == 0)
{
//we are overshooting the final waypoint, so just return some nulls in the array
//just break and we'll return the array, which is going to have nulls at the end.
Debug.Log(Current_Waypoint);
break;
}
else if (final_Waypoint.Next_Waypoint.Length > 1) // && if playerID == 0 so it only appears for players.
{
menu.Pause_for_Choice();
//if (menu.ButtonPress == true)
final_Waypoint = final_Waypoint.Next_Waypoint[menu.choice_int];
//***There's a bug here. It calls menu as per normal, and the game pauses.
//But when I click 'no', choice_int isn't updated first: this function finishes first,
//so this function gets old choice_int. THEN the button function executes.
Debug.Log("test 3 " + menu.choice_int);
}
else
{
final_Waypoint = final_Waypoint.Next_Waypoint[0];
}
}
listOfWaypoints[i] = final_Waypoint;
Debug.Log("i:" + i);
}
return listOfWaypoints;
}`
`{
public GameObject choice_Menu;
public bool isPaused = true;
public int choice_int=0;
public int choice_placeholder = 0;
public void Pause_for_Choice()
{
isPaused = true;
choice_Menu.SetActive(true);
Time.timeScale = 0;
}
public void Yes()
{
choice_placeholder = 0;
UnPause_Game();
}
public void No()
{
choice_placeholder = 1;
UnPause_Game();
}
public void UnPause_Game()
{
isPaused = false;
choice_Menu.SetActive(false);
Time.timeScale = 1;
}
}`

Take several photos with PhotoCapture Unity C#

I got a script that should be able to take more than one photo. I am using PhotoCapture and get an error making it unable to capture a second photo. I get the error "Value cannot be null" on the photoCaptureObject.StartPhotoModeAsync(cameraParameters, result => row, but I don't understand why this is.
I have commented away the photoCaptureObject = null; row so that the photoCaptureObject should not be null. The row if (photoCaptureObject == null) return; also proofs that the photoCaptureObjectis not null.
PhotoCapture photoCaptureObject = null;
Texture2D targetTexture = null;
public string path = "";
CameraParameters cameraParameters = new CameraParameters();
private void Awake()
{
var cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height);
// Create a PhotoCapture object
PhotoCapture.CreateAsync(false, captureObject =>
{
photoCaptureObject = captureObject;
cameraParameters.hologramOpacity = 0.0f;
cameraParameters.cameraResolutionWidth = cameraResolution.width;
cameraParameters.cameraResolutionHeight = cameraResolution.height;
cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
});
}
private void Update()
{
// if not initialized yet don't take input
if (photoCaptureObject == null) return;
if (Input.GetKeyDown(KeyCode.K) || Input.GetKeyDown("k"))
{
Debug.Log("k was pressed");
VuforiaBehaviour.Instance.gameObject.SetActive(false);
// Activate the camera
photoCaptureObject.StartPhotoModeAsync(cameraParameters, result =>
{
if (result.success)
{
// Take a picture
photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
}
else
{
Debug.LogError("Couldn't start photo mode!", this);
}
});
}
}
There is some code here in between that change the photo taken and so on, but I don't think that that code is part of the problem.
private void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
// Shutdown the photo capture resource
VuforiaBehaviour.Instance.gameObject.SetActive(true);
photoCaptureObject.Dispose();
//photoCaptureObject = null;
Debug.Log("Photomode stopped");
}
So what else could be null? Is it the StartPhotoModeAsync somehow? How can I fix this issue?
Thanks!
Okay so I understand now thanks to Henriks comment.
Unity specifically says this about StartPhotoModeAsync:
Only one PhotoCapture instance can start the photo mode at any given
time
I have focused more on the sentence after saying that one should always use PhotoCapture.StopPhotoModeAsyncbecause having PhotoCaptureMode on takes more power so I never thought about that the instance wouldn't start again after stopping it.
Now I only have TakePhotoAsyncin the update on key press and do not stop the PhotoMode due to that the app that I am making should always be able to capture photos.

Why Line renderer in unity not updating?

I am trying to draw a line from camera to a instantiated object.I am using the scene UnityARHitTest Example.When I touch on a vertical plane the object gets instantiated and i want to draw a line from camera to the object.When I move my device the line should show from the centre of my camera.For some reason line renderer is not showing when I call it in the Late update.
LineRenderer lins;
public GameObject Lineprefab;
bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
if (hitResults.Count > 0 && check==true)
{
foreach (var hitResult in hitResults)
{
Debug.Log ("Got hit!");
if (Select == 0)
{
Debug.Log("hit-zero!");
Instantiate(Instaobj[0], ForSelect);
check = false;
}
if (Select == 1)
{
Debug.Log("hit-one!");
Instantiate(Instaobj[1], ForSelect);
check = false;
}
if (Select == 2)
{
Debug.Log("hit-two!");
Instantiate(Instaobj[2], ForSelect);
check = false;
}
if (Select == 3)
{
Debug.Log("hit-three!");
Instantiate(Instaobj[3], ForSelect);
check = false;
}
if (Select == 4)
{
Debug.Log("hit-four!");
Instantiate(Instaobj[4], ForSelect);
check = false;
}
if (Select == 5)
{
Debug.Log("hit-five!");
Instantiate(Instaobj[5], ForSelect);
check = false;
}
m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
obj.StopPlaneTracking();
if (GameObject.Find("debugPlanePrefab(Clone)"))
GameObject.Find("debugPlanePrefab(Clone)").SetActive(false);
else
Debug.Log("no prefab");
//lins.SetPosition(0, m_HitTransform.position);
//lins.SetPosition(1, obj.m_camera.transform.position);
return true;
}
}
return false;
}
When I use lins.setposition() in the above method(which is commented) a line is shown in the output.When I use lins.setposition() in the below LateUpdate() the output is not shown nothing comes.
private void Start()
{
spawngenerator();
}
void spawngenerator()
{
GameObject newline = Instantiate(Lineprefab);
lins = newline.GetComponent<LineRenderer>();
//lins.SetPosition(0, m_HitTransform.position);
//lins.SetPosition(1, obj.m_camera.transform.position);
}
private void LateUpdate()
{
lins.SetPosition(0,obj.m_camera.transform.position );
lins.SetPosition(1,m_HitTransform.position );
}

How to stop auto fetching/loading of ads from UnityAds and Vungle?

I'm using both Unity Ads and Vungle to my game. I installed them using their .unitypackage.
I already finished the codes for displaying ads from them alternately. My problem now is how to stop them from fetching/loading after closing their 1st ads? Or have the option to stop the fetching while it fetches.
It make my game crashes due to memory pressure since 2 ads are already in the memory plus the resources for my game.
I browsed the source codes and can't find any API to stop fetching or unload a waiting-to-be-displayed ads. I looked on their documentations but there's no detail to do that.
Here is my current code:
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
public class AdsMngr : MonoManager<AdsMngr> {
enum AdsEngine{
VUNGLE,
UNITY_ADS,
MAXNUM
};
enum AdsStatus{
IDLE,
WAITING,
SHOWING,
MAXNUM
}
AdsEngine m_curAdsEngine = AdsEngine.UNITY_ADS;
AdsStatus m_curAdsStatus = AdsStatus.IDLE;
#if UNITY_IPHONE || UNITY_ANDROID
protected override void Awake(){
base.Awake ();
m_curAdsEngine = AdsEngine.UNITY_ADS; //VUNGLE;
SetupAdsCallback ();
}
protected override void OnDestroy(){
base.OnDestroy();
UnsetupAdsCallback();
}
void SetNextAdEngine (){
m_curAdsEngine = (AdsEngine)((int)(m_curAdsEngine + 1) % (int)AdsEngine.MAXNUM);
}
void Update(){
if (m_curAdsStatus == AdsStatus.WAITING) {
Debug.Log ("Waiting for ads to load: "+m_curAdsEngine+"\n");
bool bHasReadyAds = false;
switch(m_curAdsEngine){
case AdsEngine.VUNGLE: if( Vungle.isAdvertAvailable()){bHasReadyAds = true;} break;
case AdsEngine.UNITY_ADS: if( Advertisement.isReady() ){bHasReadyAds = true;} break;
}
if (bHasReadyAds) {
LoadingOverlay.Instance.Close();
PromptOverlay.Instance.Close();
ShowAd ();
}
}
}
public void StartAd(){
LoadingOverlay.Instance.Open();
//---start refetching/recaching the ads here
switch(m_curAdsEngine){
case AdsEngine.VUNGLE: {
Vungle.init( "mygame_forAndroid", "mygame_forIOS" );
}break;
case AdsEngine.UNITY_ADS: {
if (Advertisement.isSupported) {
//Advertisement.allowPrecache = true;
Advertisement.Initialize ("12345", true);
Debug.Log("Advertisement Initialized.\n");
} else {
Debug.Log("Platform not supported\n");
}
}break;
}
m_curAdsStatus = AdsStatus.WAITING;
}
public void StopWaitingAds(){
m_curAdsStatus = AdsStatus.IDLE;
//TODO: cancel the loading of ads.
//xxx: test code only
SetNextAdEngine ();
}
public void ShowAd(){
switch(m_curAdsEngine){
case AdsEngine.VUNGLE: {
Debug.Log("*** Vungle Ads is available. Now playing...\n");
Vungle.playAd();
Vungle.setSoundEnabled(false);
}break;
case AdsEngine.UNITY_ADS: {
Debug.Log("*** Unity Ads is available. Now playing...\n");
Advertisement.Show(null, new ShowOptions {
pause = true,
resultCallback = result => {
Debug.Log(result.ToString());
onAdEndedEvent();
}
});
}break;
}
m_curAdsStatus = AdsStatus.SHOWING;
}
#region Optional: Example of Subscribing to All Events
void SetupAdsCallback()
{
Vungle.onAdStartedEvent += onAdStartedEvent;
Vungle.onAdEndedEvent += onAdEndedEvent;
Vungle.onAdViewedEvent += onAdViewedEvent;
Vungle.onCachedAdAvailableEvent += onCachedAdAvailableEvent;
}
void UnsetupAdsCallback()
{
Vungle.onAdStartedEvent -= onAdStartedEvent;
Vungle.onAdEndedEvent -= onAdEndedEvent;
Vungle.onAdViewedEvent -= onAdViewedEvent;
Vungle.onCachedAdAvailableEvent -= onCachedAdAvailableEvent;
}
void onAdStartedEvent()
{
Debug.Log( "onAdStartedEvent" );
}
void onAdEndedEvent()
{
Debug.Log( "onAdEndedEvent" );
EndGameRewardOverlay.Instance.SetMultiplier(2);
EndGameRewardOverlay.Instance.Open();
if (m_curAdsEngine == AdsEngine.VUNGLE) {
Vungle.setSoundEnabled(true);
}
m_curAdsStatus = AdsStatus.IDLE;
SetNextAdEngine();
}
void onAdViewedEvent( double watched, double length )
{
Debug.Log( "onAdViewedEvent. watched: " + watched + ", length: " + length );
}
void onCachedAdAvailableEvent()
{
Debug.Log( "onCachedAdAvailableEvent" );
}
#endregion
#endif
}
Unity Ads and Vungle handle Ad Cacheing them self and there is not way to stop it. It is done as both networks show video Ads and video Ads take time to buffer if not pre cached before displaying.

Categories