I want to load different unity scenes based on the tag the game object has with a box collider 2D like a level loader. I have 4 "doors" (the game object with the collider) named top for top bottom for bottom left for left and right for right so I want to load the scene named bottom for the bottom door.
This is the code that does not work what I have currently
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
[SerializeField] private string topScene;
[SerializeField] private string bottomScene;
[SerializeField] private string leftScene;
[SerializeField] private string rightScene;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
if (collision.CompareTag("top"))
{
LoadScene(topScene);
}
else if (collision.CompareTag("bottom"))
{
LoadScene(bottomScene);
}
else if (collision.CompareTag("left"))
{
LoadScene(leftScene);
}
else if (collision.CompareTag("right"))
{
LoadScene(rightScene);
}
}
}
private void LoadScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
}
Use gameObject.CompareTag("top") on all Conditions accept First One. Because collision.gameobject.CompareTag("??") && collision.CompareTag("??") is same thing. And you compare 2 tags on same gameobject while gameobject contains only one tag at a time. So during Collision, you can check that if collision gameobject having a Player tag and in nested condition you can also check that it contains top, left, right, bottom tag which is not right.