- Home /
How do I code an OnHit-Scrip for my player which makes him reset his position on collision with Objects?
So basically, how can I code a script in c# that resets my players position to the starting point after a collision with an object that has the tag "Obstacle" ? I want it to reset upon Collision with a spinning capsule for example thats tagged "Obstacle". How can I implement that?
Thanks in advance guys I know this might be very basic but I am just getting started.
Greetings from Austria
Answer by Flaymes · Jan 28, 2021 at 06:17 PM
OnCollisionEnter or OnCollisionEnter2D if its a 2D game. It takes in a collider and to see if it hit a gameobject with the tag obstacle you do if(collision.tag == "Obstacle") then to set player position do transform.position = new Vector3(resetposition.x, resetposition.y, resetposition.z);
Thanks for the help!
Can I also ask you if it makes a difference whether or not I use 2 "=" or 1?
Health = 1; // sets health to 1 Health ==1// checks if health is 1
So == means "is equal to"
using UnityEngine;
public class PlayerCollision : $$anonymous$$onoBehaviour{
public Player$$anonymous$$ovement movement;
public Rigidbody rb;
void OnCollisionEnter()
{
if (OnCollisionEnter.tag == "Obstacle") ;
{
transform.position = new Vector3(resetposition.x, resetposition.y, resetposition.z);
}
}
}
sadly this doesnt work, because "the name collision does not exist in the context"
I know I have to reference it but what exactly do I have to reference?
private void OnCollisionEnter(Collision collision)
{
if (collision.tag == "Obstacle") ;
{
transform.position = new Vector3(resetposition.x, resetposition.y, resetposition.z);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613024120im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
OnCollisionEnter Logic Error 1 Answer
,Fast Moving Gameobject Collision and Trigger Check Failed 0 Answers