- Home /
Different types of projectiles cause different amounts of damage...
I have an enemy HP script. It functions off the very basic: two int-s, one for current health, and one for maximum health. Now I want to reduce the current health when a specific object with a specific tag collides with it. How can this be achieved? please consider that all my work is in c#.
Thanks in advance!
Please do not post me links from the unity docs. I am not stupid, I can use a search bar, but I need further support, so I asked a question here...
use a variable of type RaycastHit and attach it to your gun make sure it's pointed forward and another variable that contains the ray's length (using same velocity as the bullet is advised) (= Vector3.forward * rayLength) but I don't recommend using tags because unless tag every enemy differently if one is hit the others will bi hit aswell. what I do recommend is to use the raycast a bit like this:
function RayCol (hit : RaycastHit){
if(Input.GetButtonUp("Fire1"))
hit.collider.gameObject.currentHealth(-10);
/*sorry if I made some mistakes I'm used to work with JS but it should give u an idea*/
Answer by Khada · Mar 03, 2013 at 01:04 AM
If your using the Unity physics engine then we can use the 'OnCollisionEnter' callback on a script attached to the object that will be colliding with the enemy.
//this is called automatically when two colliders first intersect,
//(one of the colliding objects must have a rigid body)
void OnCollisionEnter(Collision collisionInfo)
{
if(collisionInfo.gameObject != null && collisionInfo.gameObject.tag == "tagName")
{
HealthScript hp = collisionInfo.gameObject.GetComponent<HealthScript>();
if(hp != null)
{
hp.ReduceHealth(/*damage here*/);
}
}
}
Or if you're moving things around yourself without rigid bodies etc, we can use raycasting (this is only really suitable for projectiles):
//replace and update these variables as needed:
Vector3 direction;
float speed;
void Update()
{
RaycastHit hitInfo;
Ray ray = new Ray(transform.position, direction.normalized);
if(Physics.Raycast(ray, out hitInfo, speed))
{
if(hitInfo.collider != null && hitInfo.collider.tag == "tagName")
{
HealthScript hp = hitInfo.collider.GetComponent<HealthScript>();
if(hp != null)
{
hp.ReduceHealth(/*damage here*/);
}
}
}
}
Amazing dude! I am pretty new to raycasting, so I stuck to the other method ins$$anonymous$$d. But I am learning, and this is a good way to learn, so yeah, all my thanks go forward to you!
Your answer
![](https://koobas.hobune.stream/wayback/20220613093708im_/https://answers.unity.com/themes/thub/images/avi.jpg)