- Home /
How do I get a spike to kill the player in 2D unity
I have been searching for like 4 hours and I cant find a script that makes a spike kill the player when the player touches it. Plz respond if you know how to.
Answer by unity_ek98vnTRplGj8Q · Jan 04, 2021 at 10:13 PM
Collisions between objects can be detected via the OnCollisionEnter2D() function. To set this up:
Make sure that both your player and the spike have a Collider2D component on them. There are different types of colliders for different shaped objects.
Assign some sort of identifier to the player and the spikes so that we can quickly detect what kind of object we are colliding with. Usually this is done via tags or layers.
Set up your OnCollisionEnter2D function. Decide whether you want the player to be responsible for detecting the spikes or vice versa. Then put a script on the object that you have chosen and implement the OnCollisionEnter2D function. Here's a very basic example:
public class SpikeDamage : MonoBehaviour{
//This script is designed to be attached to your spike gameobject //This function will be called every time we touch another collider //If you are using a collider with the "IsTrigger" option selected, use OnTriggerEnter2D instead void OnCollisionEnter2D(Collider2D col){ //When this is called, it will give us the collider we touched as a parameter //We can touch lots of different colliders, so before we try to deal damage lets check what we are colliding with //This assumes that the player gameobject has been given a tag called "Player" if(col.CompareTag("Player")){ //If we are colliding with the player, then you can now deal damage. //Do this however you want. Usually you will want to access some component on the player gameobject, then call a function that deals damage. col.GetComponent<PlayerHealth>().DealDamage(100); } } }
Your answer
Follow this Question
Related Questions
Make Player Drown in Mud Pit 1 Answer
how do you make a 3D game object destroy your player? 1 Answer
Kill System, who killed who (UNET) 1 Answer
How can I stop killing myself ? 3 Answers
2D NPC should kill player on collision but does not. 1 Answer