- Home /
Apply Damage To Player On Collison With Specific Game Object
Yes I do realize this question has been asked many time before. but i have never found one that fits my needs, and yes i am new and i am taking this project 1 step at a time
Enemy Object name = enemy
player is Main Camera
Health Script
var Health = 100;
function ApplyDammage (TheDammage : int) { Health -= TheDammage;
if(Health <= 0) { Dead(); } } function Dead() { Destroy (gameObject); }
Raycast Shooting Script
var Effect : Transform; var TheDammage = 100;
function Update () {
var hit : RaycastHit; var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0)); if (Input.GetMouseButtonDown(0)) { if (Physics.Raycast (ray, hit, 100)) { var particleClone = Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal)); Destroy(particleClone.gameObject, 2); hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver); } } }
Current attempt that dont work var health = 4; var damage = 1; var wait_time = 2; var lock = 0;
function OnCollisionEnter(hit: Collision){ if(hit.gameObject.tag == "enemy" && lock == 0) { hit.transform.SendMessage("ApplyDammage", 100, SendMessageOptions.DontRequireReceiver); } }
Add some debug to your OnCollision to see if you ever get what you expect. If #5 is attached to Player, do you have a collider (not a character controller) or rigidbody?
Answer by Seth-Bergman · Jan 12, 2014 at 07:48 AM
tag and name are two different things.. make sure you create a TAG called enemy and give your object that tag.. Or change your code to:
if(hit.gameObject.name == "enemy" && lock == 0)
also, OnCollision functions may require a Rigidbody to work.. there is a matrix toward the bottom of this link to show what will send a collision message and what won't:
http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html
you may be better off using a trigger. just set the collider on the object to "isTrigger" and change your "OnCollisionEnter" to "OnTriggerEnter".. You will still need a Rigidbody (or CharacterController), either way.. (And for the record, there are LOTS of examples out there which explain this, you probably should look harder..)
Finally, if this or any answer helps you, don't forget to accept it by clicking the checkmark.. Welcome to the forum!
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
I need some health with my health/enemy script 0 Answers
Enemy sound detection 5 Answers
Adding a counter? 1 Answer