OnTriggerEnter2D doesn't work after switching scenes - c#

I have a game that is similar to "Flappy Bird" and I have main menu where I can start game and change skin of a pigeon. My skin collection is implemented with scroll rect and in the center there is a trigger which starts an animation of scaling a pigeon, it works fine until I click "start" and the scene changes to game and when I return to my main menu and click "skins" this trigger doesn't work anymore.
Script what is attached to all scroll rect elements to detect collisions with trigger:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResizeFieldScript : MonoBehaviour
{
private Animator _anim;
private void Start()
{
_anim = GetComponent<Animator>();
}
public void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log("Trigger is working");
if(collider.tag == "ResizeField")
{
Debug.Log("Condition is working");
_anim.SetBool("isInTrigger", true);
}
}
public void OnTriggerExit2D(Collider2D collider)
{
_anim.SetBool("isInTrigger", false);
}
}
Script what is attached to an empty object to change scenes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
public class UIController : MonoBehaviour
{
[SerializeField] private List<string> sceneNameList;
private string sceneToFind;
private int index = 0;
public void SceneChanger()
{
sceneToFind = EventSystem.current.currentSelectedGameObject.name;
foreach(string str in sceneNameList)
{
if(str == sceneToFind)
{
SceneManager.LoadScene(index);
index = 0;
break;
}
index++;
}
}
public void Exit()
{
Application.Quit();
}
public void BackMenu()
{
SceneManager.LoadScene(4);
}
}

OnTriggerEnter2D doesn't work after switching scenes. We could use OnTriggerEnter2D to jump scenes.
code show as below:
private void Update() {
// If E is pressed
if (Input. GetKeyDown(KeyCode. E)) {
// scene switching
SceneManager.LoadScene(4);
}
}
private void OnTriggerEnter2D(Collider collision) {
if (collision. tag == "ResizeField") {
// The UI prompts the user to press E to jump
EnterDialog.SetActive(true);
Debug.Log("Condition is working");
// _anim.SetBool("isInTrigger", true);
}
}
Hope it helps you.

Related

How to load death scene in C#/unitygames?

haven't posted on here before but I have been trying for a while to create a game and would like a death/game over sort of scene to appear when the player loses all 3 of their lives. I have a functioning game manager and my player can lose lives (they have 3). This is all being done in unity games and is 2d (idk if that helps). I currently have other stuff in my scene loader script that works fine so I will post the whole thing but I am having issues with the bottom most code!
Thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
public string scenename;
public GameManager GM;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
SceneManager.LoadScene(scenename);
}
}
private void Deathscene()
{
if(GM.LifeTotal == 0)
{
SceneManager.LoadScene(Bob);
}
}
}
Gamemanager script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public int PotionsCollected = 0;
public int LifeTotal = 3;
public Text PotionsOutput;
public Text LifeOutput;
void Update()
{
PotionsOutput.text = "Potions: " + PotionsCollected;
LifeOutput.text = "Life: " + LifeTotal;
}
public void CollectPotion()
{
PotionsCollected++;
}
public void UsePotion()
{
PotionsCollected--;
}
public void LoseLife()
{
LifeTotal--;
}
}
What you can do is from your Unity Editor go to File->Build Settings and then drag and drop inside the active scenes window your death scene.
Then an index will be generated on the right side of the window and you can use that index to load the scene. like this:
SceneManager.LoadScene("Use your generated index");
NOTE: Use your index as a number and not as a string.
UPDATED Solution:
public void LoseLife()
{
LifeTotal--;
if(LifeTotal <= 0)
{
SceneManager.LoadScene("Use your generated index");
}
}
I supposse LoseLife() it's called when the enemy attacks your player.

Object pickup and text display

I'm trying for my player to walk over a game object and have to press "e" to pickup the object and display the text stored in it on pickup, not on collision. This is the code I have right now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NoteV2 : MonoBehaviour
{
[SerializeField] private GameObject uiObject;
[SerializeField] private GameObject note;
private SpriteRenderer sr;
private bool pickUpAllowed;
void Start()
{
uiObject.SetActive(false);
sr = GetComponent<SpriteRenderer>();
}
void Update()
{
if (pickUpAllowed && Input.GetKeyDown(KeyCode.E))
{
PickUp();
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
pickUpAllowed = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
pickUpAllowed = false;
}
}
private void PickUp()
{
Destroy(gameObject);
Debug.Log("Note running");
}
}
It kinda works. I store the note gameObject and the uiObject (the canvas) to display the text on pickup, which I haven't coded yet and then destroy the gameObject. For some reason the text displays on collision and the gameObjects gets destroyed when I exit the collider, regardless of if I press "e" or not. But if I press "e" the debug message runs, so I guess it does work.
I also want to stop player movement until they have read the text stored in it but I'll handle that once the pickup works correctly.
I had this before, which works but is pickup only on collision, not when pressing any buttons. It is a little buggy but it mostly works:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Note : MonoBehaviour
{
[SerializeField] private GameObject uiObject;
[SerializeField] private GameObject note;
private SpriteRenderer sr;
//disable/enable input
public static bool PlayerControlsDisabled = false;
// Start is called before the first frame update
void Start()
{
uiObject.SetActive(false);
sr = GetComponent<SpriteRenderer>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
uiObject.SetActive(true);
sr.color = new Color(1f,1f,1f,0);
startIn();
}
}
public void startIn()
{
StartCoroutine(waitTantico());
}
IEnumerator waitTantico()
{
PlayerControlsDisabled = true;
print("Hello World");
Debug.Log(Time.time);
yield return new WaitForSeconds(3);
Debug.Log("Waited");
PlayerControlsDisabled = false;
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerExit2D(Collider2D collision)
{
uiObject.SetActive(false);
Destroy(note);
}
}

coroutine animation not playing as expected

so everything seems to be running as far as the AI switching different States, however when it gets in range with the player the State freezes in attack and does not play any Attack Animation, I have created the AI with Bone Rigging, Im wondering if this may be affecting it, here is my script for calling the Animation and the script for one the animation has finished to go back to idleFollow state.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeleeWeapon : Weapon
{
[SerializeField] private float attackDelay = 1f;
private Collider2D damageAreaCollider2D;
private Animator animatorAttack;
private bool attacking;
private readonly int useMeleeWeapon = Animator.StringToHash(name:"UseMeleeWeapon");
private void Start()
{
damageAreaCollider2D = GetComponent<BoxCollider2D>();
animatorAttack = GetComponent<Animator>();
//animatorAttack.Play(useMeleeWeapon);
}
public override void UseWeapon()
{
StartCoroutine(routine: Attack());
}
/*protected override void Update()
{
base.Update();
// FlipMeleeWeapon();
}*/
private IEnumerator Attack()
{
if (attacking)
{
yield break;
}
// Attack
attacking = true;
damageAreaCollider2D.enabled = true;
animatorAttack.Play(useMeleeWeapon);
// Stop Attack
yield return new WaitForSeconds(attackDelay);
damageAreaCollider2D.enabled = false;
attacking = false;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "AI/Decisions/Attack Completed", fileName = "AttackCompleted")]
public class DecisionAttackCompleted : AIDecision
{
public override bool Decide(StateController controller)
{
return AttackCompleted(controller);
}
private bool AttackCompleted(StateController controller)
{
if (controller.CharacterWeapon.CurrentWeapon.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).length
> controller.CharacterWeapon.CurrentWeapon.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).normalizedTime)
{
return true;
}
return false;
}
}
Ok I fixed the issue, I ended up placing this code into the WeaponMelee script, but now im dealing with a weird glitch where the AI keeps tring to face the left instead of the player when they are close to eachother. this has to do with the boxcollider2D so ive placed a capsulecollider2d inside of him and changed the script to capsulecollider2d as well. but the issue is still happening
private void OnTriggerEnter2D(Collider2D collision)
{
StartCoroutine(routine: Attack());
}

Error MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it

I have been making a 2D game in Unity. I'm trying to make a game over screen appear every time a ball touches the player. I also added advertisements to release it. I added Restart and Continue buttons. When you press continue, an ad shows and the game continues. When Restart is pressed, it resets the game and your score. Whenever I restart the game and then press continue, the ad is played, but the game does not continue.
Here is the collision script:
using UnityEngine;
public class hitDetect : MonoBehaviour
{
public GameObject menuContainer;
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("HIT");
menuContainer.SetActive(true);
Time.timeScale = 0;
}
}
This is the script that restarts the game:
using UnityEngine;
using UnityEngine.SceneManagement;
public class RestartGame : MonoBehaviour
{
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Time.timeScale = 1;
}
}
Here is the advertisement and continue script:
using UnityEngine;
using UnityEngine.Advertisements;
public class continueGame : MonoBehaviour, IUnityAdsListener
{
string placement = "rewardedVideo";
public GameObject menuContain;
private void Start()
{
Advertisement.AddListener(this);
Advertisement.Initialize("4006857", true);
}
public void Continue(string p)
{
Advertisement.Show(p);
}
public void OnUnityAdsReady(string placementId)
{
}
public void OnUnityAdsDidError(string message)
{
}
public void OnUnityAdsDidStart(string placementId)
{
}
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
if(showResult == ShowResult.Finished)
{
menuContain.SetActive(false);
Time.timeScale = 1;
}
}
}
Once you call
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex)
a "new" scene is loaded and therefore anything currently existing is destroyed.
In continueGame you do
private void Start()
{
Advertisement.AddListener(this);
Advertisement.Initialize("4006857", true);
}
But you never remove that listener!
Thus the next time the Advertisement fires its event it is still trying to execute them of the now already destroyed continueGame instance.
Therefore you always should remove any listeners as soon as you don't need them anymore:
private void OnDestroy ()
{
Advertisement.RemoveListener(this);
}

Animation keeps getting triggered when I step on the tiles

I'm developing a TopDown 2D game on Unity with some RPG elements and I did as so, when the player steps on a set of tiles placed on the map, it triggers an animation with a UI showing some text. However, the animation gets called multiple times while the player keeps stepping on the tiles and even when he exits the trigger area.
What I need help with is how to make the animation only trigger once and, while the UI is in on the screen, the player is not allowed to move until the player presses the button in the UI (already programmed and working).
Here is the code I used to make the trigger function:
public class TriggerScript : MonoBehaviour
{
public string popUp;
public Animator animator;
void Start()
{
animator = GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.PopUp(popUp);
Debug.Log("trigger");
animator.SetTrigger("pop");
}
}
And here is the PopUpSystem that sets the text:
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator popupanimation;
public TMP_Text popUpText;
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text;
popupanimation.SetTrigger("pop");
}
}
If, in order to help me, you need more information and details, please ask me in the comment section.
Note that I am new to Unity and have zero experience with it so, if you can be patient and explain things in a simple way, I would enjoy that!
Thank you for reading.
Edit: this is the animator window:
Edit 2: The code that I use for the movement of the player:
public class PLayerController : MonoBehaviour
{
private Rigidbody2D MyRB;
private Animator myAnim;
public string popUp;
[SerializeField]
private float speed;
// Start is called before the first frame update
void Start()
{
MyRB = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
}
private void Move()
{
myAnim.SetTrigger("popUp");
}
// Update is called once per frame
void Update()
{
MyRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
myAnim.SetFloat("moveX", MyRB.velocity.x);
myAnim.SetFloat("moveY", MyRB.velocity.y);
if ((Input.GetAxisRaw("Horizontal")==1) ||(Input.GetAxisRaw("Horizontal") == -1)||(Input.GetAxisRaw("Vertical") == 1)||(Input.GetAxisRaw("Vertical") == -1))
{
myAnim.SetFloat("LastMoveX", Input.GetAxisRaw("Horizontal"));
myAnim.SetFloat("LastMoveY", Input.GetAxisRaw("Vertical"));
}
}
}
Edit 3: Code with boolean:
public class TriggerScript : MonoBehaviour
{
public string popUp;
public Animator animator;
bool condition = false;
void Start()
{
animator = GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (condition == false)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.PopUp(popUp);
Debug.Log("trigger");
animator.SetTrigger("pop");
condition = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
animator.SetTrigger("close");
}
All you have to do is to set your TriggerScript to something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerScript : MonoBehaviour
{
public string popUp;
private void OnTriggerEnter2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
if (collision.gameObject.tag == "Player")
{
pop.PopUp(popUp);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
PopUpSystem pop = GameObject.FindGameObjectWithTag("GameManager").GetComponent<PopUpSystem>();
pop.closeBox();
}
}
and then set your PopUpSystemScript to something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PopUpSystem : MonoBehaviour
{
public GameObject popUpBox;
public Animator popupanimation;
public TMP_Text popUpText;
public void PopUp(string text)
{
popUpBox.SetActive(true);
popUpText.text = text;
popupanimation.SetTrigger("pop");
}
public void closeBox()
{
popupanimation.SetTrigger("close");
}
}
Now click on the popUp and close animation clips (in Animations folder) and remove the Loop Time check mark. and you should be all set to see the animation appears and disappears.
To stop the player, you can either use Time.timeScale. or set the rigidbody to isKenimatic.

Categories