I want the cube (player) to die when it hits another cube (not player). I dont know writing scripts. Can anybody help me?
Thanks.
You should watch some tutorials if you are interested on making games. Here you have a really short one about what you asked for Detecting Collisions (OnCollisionEnter) - Unity Official Tutorials - YouTube
You will never learn if you ask someone for such a simple code instead of doing research
I don’t mean to be rude, but you’d best get acquainted with how programming works, at least just in Unity. C# is a lovely language, and you’ll have much more power to make what you want :). It is a large time investment, but it’s definitely worth it, and even just small steps every week are much better than none!
To answer your question, Unity has “messages” that get sent to MonoBehaviour scripts on a GameObject at important parts in the game. Most notably, you’ve probably heard of Awake(), Start(), and Update() in MonoBehaviour classes. You can expect Unity to magically call these methods for you at the appropriate times – you could just put a Debug.Log(“Hi”); statement in Update(), and it’ll happen every update frame (and your console will get spammed).
Similar to those messages, there exists other ones for getting information about what’s happening with the physics side of things. You can detect when objects collide, see when objects enter and leave trigger Colliders, etc.
What you’ll want to have in your MonoBehaviour class is:
public void OnCollisionEnter(Collision collision) { //When this runs, you know your object hit something! //it hit collision.collider, which is attached to collision.gameObject }
Then you can ask questions in the code using if statements about the object that collided with the current one. For example, if your block has a script on it called PainfulBlock, and you have “public class PainfulBlock : MonoBehaviour { … }” defined somewhere, then you can check if the object the player collided with has that PainfulBlock component on it like this:
public void OnCollisionEnter(Collision collision) { PainfulBlock block = collision.GetComponent<PainfulBlock>(); if (block != null) { //This player did hit a block! //Therefore, they should die -- write that code in here. } }
OnCollisionEnter(…) gets called only the first physics update where two colliders enter contact with each other. There’s also OnCollisionStay(…) and OnCollisionExit(…) to get called while they stay in contact, or exit contact with each other, respectively. Note that in order for your player’s MonoBehaviour, containing this OnCollisionEnter(…) method, to have it called properly:
-
There must be at least 2 objects in your scene with a Collider of some sort
-
One of the two colliders, for a “Collision” message, must have a non-kinematic Rigidbody component as well
-
Place your script with OnCollisionEnter(…) on the same GameObject as the player’s collider to see when the player comes into contact with other objects