• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Deadly_Skeli · Mar 04, 2020 at 07:34 PM · prefabcollision detectiondamage

How do I make my bullet prefab do damage to the enemy?

I'm trying to make a fps and decided to use prefab bullets instead of raycast, But I cant get the bullets to damage the enemy on contact.

Enemy health script

   public int EnemyHealth = 20;
     public bool EnemyDead = false;
     public GameObject EnemyAI;
     public GameObject Enemy;
 
     void DamageEnemy(int damageAmmount)
     {
 
         EnemyHealth -= damageAmmount;
         Enemy.GetComponent<Animator>().Play("Damage1");
         Enemy.GetComponent<Animator>().Play("Damage1", -1, 0);
     }
 
     void Update()
     {
         if (EnemyHealth <= 0 && EnemyDead == false)
         {
             EnemyDead = true;
             Enemy.GetComponent<Animator>().Play("Death");
             EnemyAI.SetActive(false);
             GlobalScore.ScoreValue += 700;
             GlobalComplete.EnemyCount += 1;
             this.GetComponent<BoxCollider>().enabled = false;
         }
     }

Bullet script

 public Vector3 m_target;
     public GameObject collisionExplosion;
     public float speed;
 
     void Update()
     {
         float step = speed * Time.deltaTime;
 
         if (m_target != null)
         {
             if (transform.position == m_target)
             {
                 explode();
                 return;
             }
             transform.position = Vector3.MoveTowards(transform.position, m_target, step);
         }
 
     }
 
     public void setTarget(Vector3 target)
     {
         m_target = target;
     }
 
     void explode()
     {
         if (collisionExplosion != null)
         {
             GameObject explosion = (GameObject)Instantiate(
                 collisionExplosion, transform.position, transform.rotation);
             Destroy(gameObject);
             Destroy(explosion, 1f);
         }
 
     }

How do I make the bullet script cause damage to the Enemy health script upon the bullet prefab's collision?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by pete94za · Mar 04, 2020 at 07:49 PM

Create a tag for your enemy, let's say "Enemy", and make sure you assign this tag to the Enemy. Then in your bullet script add this method:

 private void OnCollisionEnter(Collision collision)
     {
         if (collision.transform.tag == "Enemy")
         {
             // do damage here, for example:
             collision.gameObject.GetComponent<Enemy>().TakeDamage(5);
         }
     }

And in your Enemy Script, create the function:

 public void TakeDamage(int damageAmount)
         {
             health -= damageAmount;
             // other stuff you want to happen when enemy takes damage
         }

But in order to detect the collisions better, both of these objects should probably have a Rigidbody attached to them (The Enemy and the Bullet).

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Deadly_Skeli · Mar 04, 2020 at 08:19 PM 0
Share

Sadly it doesn't work, I added a Debug.Log inside of it, but it didn't give me any messages. And if I uncomment the collision.GetComponent<Enemy>().TakeDamage(); it says that Collision doesn't contain a definition for 'GetComponent'.

avatar image pete94za Deadly_Skeli · Mar 04, 2020 at 08:55 PM 0
Share

I edited my answer. ins$$anonymous$$d of collision.GetComponent it should be collision.gameObject.GetComponent and also be sure to actually implement the function in your Enemy script. I just gave you an example of what you could do. But I've now included the TakeDamage function too for you.

avatar image tormentoarmagedoom Deadly_Skeli · Mar 04, 2020 at 08:57 PM 1
Share

HEllo.

REad the OnCollision manual. Be sure you do all necessary things in the editor

avatar image pete94za Deadly_Skeli · Mar 04, 2020 at 08:59 PM 0
Share

Also in the GetComponent part, be sure to change the Enemy() to whatever your Enemy script is called.

Show more comments
avatar image
0

Answer by Fragsteel · Mar 04, 2020 at 10:53 PM

The answer from @pete94za will work and is the most direct answer to OP's question. But for future reference, it can help to implement an interface for anything that can take damage. In most games, there are multiple things that can take damage, not just a single "enemy" class. If you're searching for a class like Enemy in GetComponent, then the only way to have a bullet be able to damage multiple kinds of things is to do different checks for every kind of potential object, eg. GetComponent<Crate>(), GetComponent<Window>(), etc. (it can be a tad simpler using inheritance, but you get the point and interfaces are still better)

Instead, such interface could look like:

  public interface IDamageable 
 {
      void TakeDamage(float damage);
 }

Then, any class that should be damageable by the bullet (or anything else that does damage) can implement IDamageable, and have a method like TakeDamage(float damage). Each class like Enemy, Window, Crate, etc. can write that method differently, but implementing that interface guarantees that the method exists. It could look like:

 public class Enemy : MonoBehaviour, IDamageable
  {
      float hp = 10;
      void IDamageable.TakeDamage(float damage)
      {
          hp -= damage;
          Debug.Log(gameObject.name + " took " + damage + " damage.");
          if(hp <= 0)
          {
               Destroy(gameObject);
          }
      }
  }


Then in your bullet, you do:

  IDamageable damageable = collision.gameObject.GetComponent();
  
  if(damageable != null)
  {
      damageable.TakeDamage(5);
  }


That will work on any class that implements IDamageable, regardless of its actual type.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Natrx · Aug 22, 2020 at 03:33 PM

If the enemy is in a gameobject then do: gameObject.GetComponentInParent(typeof(Enemy)) as Enemy; or you can use my script here: using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Bullet : MonoBehaviour {

 public float speed = 20f;
 public int damage = 10;
 public Rigidbody2D rb;
 public GameObject Enemy;
 public GameObject impactEffect;

 // Use this for initialization
 void Start () {
     rb.velocity = transform.right * speed;
 }

 void OnTriggerEnter2D (Collider2D hitInfo)
 {
     if(hitInfo.CompareTag("Enemy")){
     Enemy enemy = hitInfo.transform.gameObject.GetComponentInParent(typeof(Enemy)) as Enemy;
     if (enemy != null)
     {
         enemy.TakeDamage(damage);
     }

     Instantiate(impactEffect, transform.position, transform.rotation);

     Destroy(gameObject);
     }
 }

}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

164 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Have damage done to player via colliders, only a certain amount of times? 1 Answer

Prefab shooting damage/health? 1 Answer

Collision doesn't work with prefabs 0 Answers

Help On Checking OverLaping in instantiating 0 Answers

Is there a better way to check for a collision with a prefab than by name or tag? 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges