I have two scenes in my project. There is only one award-winning video for each scene.
In first scene, Everthing is okey, but if you come to second scene to first scene, i can't give reward to users and endofRewarded panel is not visible. What is the correct method for giving reward? How can i do that?
P.s : I know the tutorial is here.
https://developers.ironsrc.com/ironsource-mobile/unity/rewarded-video-integration-unity/
But, I am beginner.
Thank you.
Here is my code for first scene :
public class RewardedMain : MonoBehaviour
{
public string appkey;
public GameObject endofRewarded, anaEkran;
// Start is called before the first frame update
void Start()
{
IronSource.Agent.shouldTrackNetworkState(true);
IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvaibilityChangedEvent;
IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
//IronSourceEvents.onRewardedVideoAdReadyEvent += OnRewardedVideoAdReady;
}//END START
public void showRewarded()
{
if (IronSource.Agent.isRewardedVideoAvailable())
{
anaEkran.SetActive(false);
IronSource.Agent.showRewardedVideo("MainRewarded");
}
}
void RewardedVideoAdClosedEvent()
{
IronSource.Agent.init(appkey, IronSourceAdUnits.REWARDED_VIDEO);
IronSource.Agent.shouldTrackNetworkState(true);
}
void RewardedVideoAvaibilityChangedEvent(bool available)
{
bool rewardedVideoAvailability = available;
}
void RewardedVideoAdRewardedEvent(IronSourcePlacement ssp)
{
PlayerPrefs.SetInt("totalCoin", PlayerPrefs.GetInt("totalCoin") + 150);
GameObject.Find("GoldNumberText").GetComponent<Text>().text = PlayerPrefs.GetInt("totalCoin").ToString();
SoundManager.Instance.PlayEarnGoldSound();
endofRewarded.SetActive(true);
}
I'm not quite sure what your project looks like, so I'll give some hints as per the information you've given me now.
The problem you're having is that when you get to the second scene, the objects that are hooked up to this mono script will disappear?
If so, add the following code to awake and your GameObject will exist across scenes!
DontDestroyOnLoad(gameObject);
Related
I have a script in my Unity game that rotates and moves the VR player's camera. Currently, I have the code running in an update loop but the update loop runs during the frame (I assume). This makes the camera feel like it moves late and can be really disorienting.
Is there a way to execute my code before the frame is drawn?
private void Update() {
head.localPosition = VRInputHandler.HeadsetPosition;
head.localRotation = VRInputHandler.HeadsetRotation;
}
After much digging around, I found a solution that looks to work well. It's as simple as subscribing to an event called "onAfterUpdate".
I'll paste the code that worked for me below:
private void OnEnable() {
InputSystem.onAfterUpdate += EarlyUpdate;
}
private void OnDisable() {
InputSystem.onAfterUpdate -= EarlyUpdate;
}
private void EarlyUpdate() {
head.localPosition = VRInputHandler.HeadsetPosition;
head.localRotation = VRInputHandler.HeadsetRotation;
}
Note: I don't think this event was designed to do this but it works.
So I'm basically brand new to unity and C# and have been following along with tutorials online (N3K 2D Platformer, YouTube), I'm trying to create a basic UI to display score etc and I seem to have come across a null pointer exception which I can't seem to figure out as I have referenced the two objects that are causing this error, namely my scoreText object and my hitPointText object.
As I've said I did reference those very objects by dragging them from my hierarchy and into the fields I had created in my level manager script in the inspector and further to that I am simply following along with a tutorial and have done exactly as the video has instructed, but yet on the video it seems to work fine.
The offending lines of code are:
scoreText.text = score.ToString();
hitPointText.text = hitPoints.ToString();
This tutorial is now over 1 year old, is it possible that a unity update has changed that way things NEED to be referenced?
I'll post my level manager code below in the hopes that someone may be able to point out the error that I seem to be missing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelManager : MonoBehaviour
{
public static LevelManager Instance { set; get; }
public Transform spawnPosition;
public Transform playerTransform;
private int hitPoints = 3;
private int score = 0;
public Text scoreText;
public Text hitPointText;
private void Awake()
{
Instance = this;
scoreText.text = score.ToString();
hitPointText.text = hitPoints.ToString();
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
private void Update ()
{
if(playerTransform.position.y < (-10))
{
playerTransform.position = spawnPosition.position;
hitPoints--;
if(hitPoints <= 0)
{
Debug.Log("Your Dead!");
}
}
}
public void Win()
{
Debug.Log("Victory");
}
}
Snippets of screens below:
Scene view of unity engine
Game view of unity engine, with game running
So here is a snippet of code from my player class which uses Instance on the LevelManager script in order that it can have access to the win() method as can be seen in the last case of the switch "WinPost", not sure if that is what you are referring to when your mentioning singleton, other than that never is the term singleton used in any of the scripts I have.
switch (hit.gameObject.tag)
{
case "Coin":
Destroy(hit.gameObject);
break;
case "JumpPad":
verticalVelocity = jumpForce * 2;
break;
case "Teleporter_1":
controller.enabled = false;
transform.position = hit.transform.GetChild(0).position;
controller.enabled = true;
Debug.Log("This works!");
break;
case "Teleporter_2":
controller.enabled = false;
transform.position = hit.transform.GetChild(0).position;
controller.enabled = true;
Debug.Log("This works!");
break;
case "WinPost":
LevelManager.Instance.Win();
break;
default:
break;
}
My guess would be that the components aren't initialized when you call Awake. Awake gets called as a constructor-kind-of method as soon as the object is created. When it is called, you can't be sure if the other components got initialized already.
I would suggest you copy the assignments you make in Awake into Start and come back to see if it works. Start gets called after the GameObjects have their components initialized.
private void Awake()
{
Instance = this;
}
// Use this for initialization
void Start ()
{
scoreText.text = score.ToString();
hitPointText.text = hitPoints.ToString();
}
Thanks to everyone for trying to help and all the great suggestions.
Ultimately I ended up breaking my game in the process of trying to recreate the same UI in a new blank scene, I did manage to recreate the same error before breaking my game which at the time then left me none the wiser. However due to the fact I broke my game I had to step back at least two tutorials and recreate the level manager object and the empty child spawnPosition object, (the level manager script was ok, it was just the level manager object and its child that I broke), anyway in having to recreate both of those objects again everything now seems to work as intended and so this leads me to the conclusion that the problem was not the code but the objects themselves???
Thanks again to everyone that tried to help, another day another learning experience.
D.
I was wondering if there was a way in Unity that when I start my program on a scene it fires a function first, I should add that I want this one function to work regardless of what scene I'm in. So a simple Start function wont cut it. Not sure if this is possible in Unity?
public void ProgramBegins()
{
//FIRES FIRST ON ANY SCENE
//DO STUFF
}
RuntimeInitializeOnLoadMethodAttribute can help you :)
using UnityEngine;
class MyClass
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void OnBeforeSceneLoadRuntimeMethod()
{
Debug.Log("Before scene loaded");
}
}
Here you can find the execution order of all functions in unity: http://docs.unity3d.com/Manual/ExecutionOrder.html
Awake is the first function to be executed in your standalone application. For it to run you need to have a GameObject with a attached script containing the Awake function. This should be added to every scene if you want it to run regardless of the scene.
You still have to decide what is the startup scene of your game. So it is enough to add the GameObject there, if you actually want it to run just in the start of the program.
I use a prefab _AppStartup which is just an empty game object having a script AppStartup. Drag this in every scene and configure AppStartup to be executed as first like #maZZZu has stated.
AppStartup performs the following jobs:
Global initialisation tasks when the app is started
Switch to boot scene if have start an arbitrary scene in editor mode
Scene specific initialisation tasks
public class AppStartup : MonoBehaviour
{
const int bootSceneNo = 0;
public static bool veryFirstCallInApp = true;
void Awake ()
{
if (veryFirstCallInApp) {
ProgramBegins ();
if (Application.loadedLevel != bootSceneNo) {
// not the right scene, load boot scene and CU later
Application.LoadLevel (bootSceneNo);
// return as this scene will be destroyed now
return;
} else {
// boot scene stuff goes here
}
} else {
// stuff that must not be done in very first initialisation but afterwards
}
InitialiseScene ();
veryFirstCallInApp = false;
DestroyObject (gameObject);
}
void ProgramBegins()
{
// code executed only once when the app is started
}
void InitialiseScene ()
{
// code to initialise scene
}
}
So all you have to do is drag this prefab in every scene manually and give it -100 or whatever in the script execution order. Especially when the project grows and relies on a predefined scene flow it will save you al lot time and hassle.
Yes...
Decorate your method with [RuntimeInitializeOnLoadMethod].
It will be invoked as soon as the scene has finished loading (after Awake events).
[RuntimeInitializeOnLoadMethod]
static void OnRuntimeMethodLoad() {
Debug.Log("After Scene is loaded and game is running");
}
Documentation: https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
//try this it work in my case
public static bool isFirstLoad;
void Awake()
{
//your work that run only once even restart this scene
mainPanel.SetActive(!isFirstLoad);
if(!isFirstLoad)
{
isFirstLoad=true;
}
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
I have an object that when clicked it is destroyed and spawns randomly somewhere else on a timer. I'm trying to make it so instead of random spots it shows up at fixed locations.
I also want them to randomly spawn at those fixed locations on a timed interval, one at a time.(so if it appears in one location for lets say 5 seconds, it will be destroyed and the next one will appear in a different location.)
I attempted to do fixed spawn locations, but the void spawner doesn't want to work.
I get a "The object of type "GameObject" has been destroyed but you are still trying to access it".
I can fix this by commenting out the On_TouchStart destroy line, but I need it.
Here is my code:
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
public float AppearTime = 0f;
public Transform[] teleport;
public GameObject[] prefab;
void Spawner(){
int tele_num = Random.Range(0,5);
int prefab_num = Random.Range(0,3);
if (prefab !=null){
Instantiate(prefab[prefab_num], teleport[tele_num].position, teleport[tele_num].rotation );
}
}
void StartTime()
{
StartCoroutine(DoTime());
}
void OnEnable(){
EasyTouch.On_TouchStart += On_TouchStart;
}
IEnumerator DoTime()
{
yield return new WaitForSeconds(AppearTime);
Spawner();
}
void On_TouchStart (Gesture gesture){
if (gesture.pickObject != null){
Destroy(gesture.pickObject);
StartTime();
}
}
If anyone could lead me on the right track I'd appreciate it.
Thanks.
I figured it out. Turns out the prefabs I were using were incorrect, so I needed to swap them out for ones that did.
Thanks to the ones who helped.
Ok, so continuing with my game, Im able to instantiate enemies and assign individual sprites to them on startup. When I destroy the enemies, and they all are destroyed when one is hit, I call that same function again. The inspector shows the gameobjects are there, but the sprite renderer component is blank. No error messages are displayed.
Here's my code simplified. This is where my instantiation and rendering method is at:
public class EnemySpawner : MonoBehaviour {
public Sprite[] HiraganaSprites;
public void setEnemies()
{
int counter=0;
while (counter<5)
{
Instantiate (EnemyPrefab, enemyPos, player.transform.rotation);
//label the enemy
EnemyPrefab.tag = "Enemy" + counter;
counter++;
}
//render diff sprites for each
counter=0;
while (counter<5)
{
string en_name="Enemy"+counter;
labelEnemy = GameObject.FindGameObjectWithTag (en_name);
SpriteRenderer renderer=labelEnemy.GetComponent<SpriteRenderer>();
renderer.sprite=Sprites[counter];
counter ++;
}
void Awake()
{
Sprites = Resources.LoadAll<Sprite> ("kana");
}
}
}
I make the call from a different script.
public EnemySpawner enemyspawner;
void function()
{
enemyspawner=gameObject.AddComponent<EnemySpawner>();
enemyspawner.setEnemies();
}
First time around, everything works fine!
Second time, nothing .
Weird thing is the prefabs are there, set on position, just not rendered. Also no error messages.
This is how Im destroying the enemies in case that helps.
while (i<=numenemies)
{
string tag="Enemy"+i;
destroyenemy=GameObject.FindGameObjectWithTag(tag);
Destroy(destroyenemy.gameObject);
i++;
}
You should attach EnemySpawner Script to gameObject and then update the script in which you call setEnemies function as follows -
public EnemySpawner enemyspawner;
void function()
{
enemyspawner=gameObject.GetComponent<EnemySpawner>();
enemyspawner.setEnemies();
}