Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Linq;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.AI;
- using UnityEngine.SceneManagement;
- namespace SceneManagement
- {
- [Serializable]
- public class Portal : MonoBehaviour
- {
- [SerializeField] private Transform spawnPoint;
- [SerializeField, HideInInspector] private PortalSo portalData;
- public PortalSo SelectedPortal
- {
- get => portalData;
- set => portalData = value;
- }
- private void OnTriggerEnter(Collider other)
- {
- if (other.CompareTag("Player"))
- {
- StartCoroutine(Transition());
- }
- }
- private IEnumerator Transition()
- {
- DontDestroyOnLoad(gameObject);
- yield return SceneManager.LoadSceneAsync(portalData.SceneToLoad);
- Portal otherPortal = GetOtherPortal();
- UpdatePlayer(otherPortal);
- Destroy(gameObject);
- }
- private void UpdatePlayer(Portal otherPortal)
- {
- GameObject player = GameObject.FindWithTag("Player");
- player.GetComponent<NavMeshAgent>().Warp(otherPortal.spawnPoint.position);
- player.transform.rotation = otherPortal.spawnPoint.rotation;
- }
- private Portal GetOtherPortal()
- {
- var portals = FindObjectsOfType<Portal>();
- return portals.FirstOrDefault(portal => portal.portalData == portalData.DestinationPortal);
- }
- private void OnDrawGizmos()
- {
- BoxCollider col = GetComponent<BoxCollider>();
- DrawBoxCollider(new Color(0, 0, 255, .25f), col);
- }
- private void DrawBoxCollider(Color color, BoxCollider boxCollider)
- {
- Gizmos.matrix = Matrix4x4.TRS(transform.TransformPoint(boxCollider.center), transform.rotation, transform.lossyScale);
- Gizmos.color = color;
- Gizmos.DrawCube(Vector3.zero, boxCollider.size);
- }
- }
- #if UNITY_EDITOR
- [CustomEditor(typeof(Portal))]
- public class PortalEditor : Editor
- {
- private PortalSo[] portals;
- private Portal portal;
- private int selectedIndex;
- private string[] portalNames;
- private void OnEnable()
- {
- portal = target as Portal;
- if (portal is null)
- return;
- portals = GetAllInstances<PortalSo>();
- portalNames = new string[portals.Length];
- selectedIndex = portals.ToList().IndexOf(portal.SelectedPortal);
- for (int i = 0; i < portals.Length; i++)
- portalNames[i] = portals[i].name;
- }
- public override void OnInspectorGUI()
- {
- base.OnInspectorGUI();
- selectedIndex = EditorGUILayout.Popup(new GUIContent("Portal Data"), selectedIndex, portalNames);
- portal.SelectedPortal = portals[selectedIndex];
- EditorUtility.SetDirty(target);
- }
- private T[] GetAllInstances<T>() where T : ScriptableObject
- {
- string[] guids = AssetDatabase.FindAssets("t:" + typeof(T).Name);
- var a = new T[guids.Length];
- for (int i = 0; i < guids.Length; i++)
- {
- string path = AssetDatabase.GUIDToAssetPath(guids[i]);
- a[i] = AssetDatabase.LoadAssetAtPath<T>(path);
- }
- return a;
- }
- }
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement