So I’m working on an FPS game with a portal feature, and I can’t really get the teleportation to work. I can instantiate the portals fine, but when I collide with the portal entrance to teleport, instead of teleporting to the portal exit point, the player is teleported to 0,0,0. Can someone please suggest a fix and/or tell me why this is occurring? There are no errors being thrown, just this problem.
I am working in Unity 2018.4.25.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PortalController : MonoBehaviour
{
float range = 75f;
int netCount;
//The prefabs of the portals
public GameObject portalEnter;
public GameObject portalExit;
//The clones of the portals so that the game doesn't delete the prefabs
GameObject portalEnterClone;
GameObject portalExitClone;
[SerializeField] GameObject switcher;
public GameObject player;
public Camera playerCam;
public Transform portalEnterLocation;
public Transform playerTransform;
Vector3 portalExitPos;
void Start()
{
netCount = 0;
}
void Update()
{
if (Input.GetButtonDown("Fire1") && netCount == 0)
{
SetNet();
}
if(portalExitClone = null)
{
Destroy(portalEnterClone);
}
}
void SetNet()
{
//Instantiates the first portal right next to the player. Followed the instructions, but is still trying to delete prefabs
portalEnterClone = Instantiate(portalEnter, portalEnterLocation.position, Quaternion.identity);
//seting the second portal using raycasting.
RaycastHit hit;
if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, range))
{
portalExitClone = Instantiate(portalExit, hit.transform.position, Quaternion.identity);
portalExitPos = portalExit.transform.position;
netCount++;
switcher.GetComponent<WeaponSwitcher>().SwitchToPistol();
switcher.GetComponent<WeaponSwitcher>().StartPortalCooldown();
}
else
{
//Instantiating the exit of the portal network, starting from the player's camera and following your code.
portalExitClone = Instantiate(portalExit, playerCam.transform.position + range * playerCam.transform.forward.normalized, Quaternion.identity);
}
}
public void Teleported()
{
//Calling from PlayerController.cs after collision with portal entrance
playerTransform.position = portalExitPos;
Destroy(portalEnterClone);
Destroy(portalExitClone);
netCount--;
}
}