Hello coders!
Is there any particular reason I cannot change the position of DontDestroyOnLoad object at runtime?
I have 2 scenes, on scene 1 I set my object (basically a container with a character controller attached and my fbx avatar inside) because I need it to persist across scenes.
Then on scene 2, I try to reference my container to get it’s position in order to change it later (I’m trying to make a portal, so the avatar car jump from one position to another) so I
For that I’m using Brackeys tutorial find it here but I can’t manage to make it work.
So I decided to just force the position by pressing a button (M) to send the object to the origin (0, 0, 0) and to my surprise, it didn’t worked either, so I’m clueless about what happening with my object, but I think it must have something to do with it being a DontDestroyOnLoad.
Here I leave you my code and some important stuff:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Portal : MonoBehaviour
{
public GameObject container;
public Transform player;
public Transform receiver;
private bool playerIsOverlapping = false;
// Start is called before the first frame update
void Awake()
{
//Look on the hierachy for the Container then get its component transform and assign it to the player variable.
container = GameObject.Find("AvatarContainer");
player = container.GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
if (playerIsOverlapping)
{
Vector3 portalToPlayer = player.position - transform.position;
float dotproduct = Vector3.Dot(transform.up, portalToPlayer);
//If this is true, the player crossed the portal from the front side
if (dotproduct < 0f)
{
float rotationDiff = -Quaternion.Angle(transform.rotation, receiver.rotation);
rotationDiff += 180;
player.Rotate(Vector3.up, rotationDiff);
Vector3 positionOffset = Quaternion.Euler(0f, rotationDiff, 0f) * portalToPlayer;
player.position = receiver.position + positionOffset;
playerIsOverlapping = false;
}
}
if (Input.GetKeyDown(KeyCode.M))
{
player.position = new Vector3(0, 0, 0);
Debug.Log("Player Positions is " + player.position);
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Container")
{
Debug.Log("Collide with " + other);
playerIsOverlapping = true;
}
}
void OnTriggerExit(Collider other)
{
if(other.tag == "Container")
{
playerIsOverlapping = false;
}
}
}
Images (click to view):
Oddly enough, my debug on line 45 says the position it’s at (0, 0, 0) but my container doesn’t move to the new position.
Any insights will b appreciated.