Problems with respawning using a very simple script
I have two small scripts that work together. One is 'HurtPlayer' which detects when a player enters a hit box and gives it damage:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HurtPlayer : MonoBehaviour
{
public int damageToGive = 1;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
FindObjectOfType<HealthManager>().HurtPlayer(damageToGive);
}
}
}
The other is 'HealthManager' which keeps track of hp, and triggers respawn when hp goes to 0 or below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthManager : MonoBehaviour
{ public int maxHealth; public int currentHealth;
public PlayerControllercc thePlayer;
private Vector3 respawnPoint;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
respawnPoint = thePlayer.transform.position;
}
public void HurtPlayer(int damage)
{
currentHealth -= damage;
if (currentHealth <= 0)
{
Respawn();
}
}
public void Respawn()
{
thePlayer.transform.position = respawnPoint;
}
My player controller script is named 'PlayerControllercc' (cause it uses character controller), and I just drag and drop my player into the corresponding slot in the inspector. I set Max health to 2.
I can see in the inspector that currentHealth does go down with each collision, and that respawnPoint is set to the transform of the player when I start the game. Everything seems to work as it should... except the last line where the player needs to be teleported. I've set up tests to make sure this function is being called, and it is so I don't understand why this line won't work. I've been messing around with this for hours and surely this must have a simple fix, or I'm missing something obvious.
Also, I'm sorry about formatting in this post. I'm not sure how to make it realize which parts are code and which aren't.
Please help!
Answer by BBerryman · Apr 04, 2019 at 12:30 AM
In case anyone looks at this in the future, the problem was with Unity's built in character controller. It has a bug where it overwrites the player position. The solution was to manually disable the controller, teleport, then enable it again like so:
public void Respawn()
{
thePlayer.controller.enabled = false;
thePlayer.transform.position = respawnPoint;
thePlayer.controller.enabled = true;
}