- Home /
Float not resetting when I instantiate new player prefab
Hi there, in my code I explicitly tell the player script to reset its health value when it is instantiated. I have tried resetting the float in the awake function, the start, in its own function but when a new player prefab clone is instantiated it keeps the same health value as the previous player prefab. In this case spawning a player with a negative health value so that when it is attacked it dies instantly and spawns a new player prefab with even less health.
public class Player : MonoBehaviour {
[System.Serializable]
public class PlayerStats
{
public float Health = 100f;
}
public PlayerStats stats = new PlayerStats();
public int fallBoundary = -20;
private void Awake()
{
Reset();
}
public void Start()
{
}
private void Update()
{
if (transform.position.y < fallBoundary)
DamagePlayer(999999);
}
public void DamagePlayer(float damage)
{
stats.Health -= damage;
if (stats.Health <= 0)
{
if (this != null)
GameMaster.KillPlayer(this);
}
Debug.Log("player health is now" + stats.Health);
}
public void Reset()
{
stats.Health = 100f;
Debug.Log("Player health has been reset!");
}
I cannot think for the life of me why the float value would carry over to the next instance of the script. If it is truly being instantiated again surely it would call the Reset() function and set the health back to 100?
Answer by shadowpuppet · Sep 26, 2017 at 03:06 PM
try OnEnable. When the prefab is instantiated the script runs that. I use it all the time - especially in ragdoll instantiated prefabs where Void OnEnable starts a coroutine to fade away the corpse after a certain amount of time then destroy the prefab or even respawn a new enemy
void OnEnable(){
Reset();
} }
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can i modify a float in another script in C#? 1 Answer
Stats effecting the max Health Value 2 Answers