The question is answered, right answer was accepted
Why is the Player Transform only changing correctly the first time?
So I am trying to make a 3D platformer for practice and I am confused on why the player spawn works on awake but then when it is triggered for respawning it doesn't work. Here is the Spawner Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
Vector3 playerSpawn;
[SerializeField] Transform Player;
private void Awake()
{
Spawn(Player); //calls spawn
Debug.Log("Spawning Finished");
}
public void Spawn(Transform p)
{
playerSpawn = GameObject.FindGameObjectWithTag("Respawn").transform.position; //sets playerSpawn to Spawner position
Debug.Log(playerSpawn);
p.transform.position = playerSpawn; //Sets Player transform to playerSpawn
Debug.Log(p.transform.position);
Debug.Log("Spawn Triggered");
}
}
And here is my script for respawning:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillBox : MonoBehaviour
{
public GameObject spawnerObject;
public Spawner spawnerScript;
[SerializeField] Transform Player;
Vector3 playerSpawn;
// Start is called before the first frame update
void Start()
{
spawnerScript = spawnerObject.GetComponent<Spawner>();
}
public void OnTriggerEnter(Collider other)
{
spawnerScript.Spawn(Player);
}
}
Are you sure that OnTriggerEnter gets called? Test it with Debug.Log. What about the Player transform, are they pointing to the same transform?
Also, if you don't need playerSpawn globally, you could use it locally, like this:
Vector3 playerSpawn = GameObject.FindGameObjectWithTag("Respawn").transform.position;
Keep in $$anonymous$$d that searching for gameobjects on runtime can decrease your performance if you have a lot of gameobjects in your scene. Either store the position in your code or get it through a reference.
Yes, OnTriggerEnter does get called, and looks like it runs through the spawning script in the stack and returns back out. I manually placed the player transform in and they both point to the same player object. It looks like it goes through the script but doesn't change the XYZ transform for some reason. And no warnings or errors pass through.
Answer by Matt27832 · Apr 06, 2021 at 07:59 PM
Figured it out. So it turns out I just had to disable the player controller before calling the spawn method or I assume it would overwrite the transform change since the gravity is also changing the transform. And then just re-enable the controller after the method is called.
Follow this Question
Related Questions
NetworkTransform did not working with RegisterSpawnHandlers 2 Answers
Player respawn after collision 0 Answers
Diagonal character movement 0 Answers
How to Increase Value as Player Approaches 0 Answers
How to automatically assign a Transform? 2 Answers