- Home /
Why won't my player die and respawn
I'm trying to make a script that kills my player when it touches the lava. For some reason, it doesn't kill it. Why?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Walking : MonoBehaviour { //Player rb public Rigidbody rb;
public float MoveSpeed = 500f;
public GameObject player;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
//Arrow movement:
if (Input.GetKey(KeyCode.RightArrow))
{
rb.AddForce(Vector3.right * MoveSpeed * Time.deltaTime);
Debug.Log("RightArrow");
}
if (Input.GetKey(KeyCode.LeftArrow))
{
rb.AddForce(Vector3.left * MoveSpeed * Time.deltaTime);
Debug.Log("LeftArrow");
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Lava")
{
Destroy(collision.gameObject);
Instantiate(player, new Vector3 (0,0,0), Quaternion.identity);
}
}
}
Answer by logicandchaos · Jan 27, 2020 at 12:34 AM
Destroy(collision.gameObject); destroys the lava not your player, it should be Destroy(gameObject); to destroy the player assuming this script is on the player object. You should put Debug.Log("collision"); right before you destroy your player to make sure it's getting called. Also rather than destroy the player and create a new one you should just move the player and reset it. Much more efficient and easier to do. I would create a function Reset() that you call instead of Destroy().
Answer by TooManyPixelz · Jan 27, 2020 at 01:01 AM
@logicandchaos hey man I actually did this.
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Lava")
{
Debug.Log("Collision");
Reset();
}
}
public void Reset()
{
player.position = RespawnPoint;
}
For some reason it still doesn't move the player, why?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Player to Gui Object Communication in C# 1 Answer
Moving player along path? 1 Answer
Problem with player movements 1 Answer