Newer
Older
Dreamsturbia-Project-IADE-Unity3D / Assets / Scripts / PortalBehaviour.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

public class PortalBehaviour : MonoBehaviour
{
    public Vector3 destination;
    [Tooltip("target scene use -1 to disable it")] public int sceneId = -1;
    [Tooltip("game objects to enable on teleporting")]public GameObject[] entities;
    [Tooltip("the teleport destination becomes relative to the Portal")]public bool relative;
    public UnityEvent<PortalBehaviour,Transform> onTeleported;
    [Tooltip("enables the Collision Detection (Trigger) automatic teleport")]public bool enableAutomaticTeleport = true;
    // Start is called before the first frame update


    private void OnTriggerStay(Collider collision)
    {
        if (enableAutomaticTeleport)
        {
            if (collision.gameObject.CompareTag("Player"))
            {
                Teleport(collision.transform);
            }
        }
    }

    public void Teleport(Transform target)
    {
        StoredTeleport.position = destination;
        StoredTeleport.teleported = true;
        if (relative)
        {
            target.position = transform.position + destination;
        }
        else
        {
            target.position = destination;
        }
        if (sceneId != -1)
        {
            SceneManager.LoadScene(sceneId);
        }

        if (entities != null && entities.Length > 0)
        {
            foreach (GameObject entity in entities)
            {
                if (entity != null)
                {
                    if (!entity.activeSelf)
                    {
                        entity.SetActive(true);
                    }
                }
            }
        }
        onTeleported?.Invoke(this,target);
    }
}