Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 WhiteDevil197 · May 21, 2015 at 06:21 AM · foreachmultiple objectshealth-deductionhealth

Problem with substracting life to multiple gameObjects (c#)

I'm developping a 2D pixel based space shooter for mobile platform and i'm struggling with a problem. I'm trying to create a rocket with a area of destruction. I'm trying to substract an amount of life to each gameObjects in a specific circle. Everything's fine until i try to apply the damages. Every enemy has a "healthscript" and a "shotdetection" script. I try to do it through a foreach, but the life always decrease on the "healthscript" of the aimed gameobject. Here are my code (i found it through different only tutorial for some part because it's my first project):

HealthScript :

 using UnityEngine;
 
 /// <summary>
 /// Gestion des points de vie et des dégâts
 /// </summary>
 public class HealthScript : MonoBehaviour
 {
     /// <summary>
     /// Points de vies
     /// </summary>
     public int hp = 1;
 
 
     
     private int damage;
     /// <summary>
     /// Ennemi ou joueur ?
     /// </summary>
     public bool isEnemy = true;
 
     public void ApplyDamage() {
         damage = gameObject.GetComponent<ShotDetection> ().damage;
         hp -= damage;
         // Destruction du projectile
         // On détruit toujours le gameObject associé
         // sinon c'est le script qui serait détruit avec ""this""
         
         if (hp <= 0)
         {
             SpecialEffectsHelper.Instance.Explosion(transform.position);    // Destruction !
             if (gameObject.name == "Player") {
                 gameObject.SetActive (false);
             }
             else {
                 Destroy(gameObject);
             }
         }
     }    
 }


ShotDetection :

 using UnityEngine;
 using System.Collections;
 
 public class ShotDetection : MonoBehaviour {
 
     
     //variables du type de shot
     private GameObject Shot;
     private GameObject DualShot;
     private GameObject Rocket;
     private GameObject DualRocket;
     //variable explosion rocket
     private float radius = 10;
     private Collider2D[] objectsInRange;
     /// <summary>
     /// Ennemi ou joueur ?
     /// </summary>
     public int damage;
 
     void Start() {
         GameObject go = GameObject.Find ("Player");
         Shot = go.GetComponent<PlayerScript> ().OneShot;
         DualShot = go.GetComponent<PlayerScript> ().DualShot;
         Rocket = go.GetComponent<PlayerScript> ().OneRocket;
         DualRocket = go.GetComponent<PlayerScript> ().DualRocket;
 
     }
 
     void OnTriggerEnter2D(Collider2D collider)
     {
         
         // Est-ce un tir ?
         ShotScript shot = collider.gameObject.GetComponent<ShotScript> ();
         bool isEnemy = gameObject.GetComponent<HealthScript> ().isEnemy;
         if (shot != null) {
             if (Shot.activeSelf || DualShot.activeSelf) {
                 // Tir allié
                 if (shot.isEnemyShot != isEnemy) {    
                     GetComponent<HealthScript>().ApplyDamage();
                 }
             } else if (Rocket.activeSelf || DualRocket.activeSelf) {
                 if (shot.isEnemyShot != isEnemy) {
                     Vector2 location = collider.transform.position;
                     objectsInRange = Physics2D.OverlapCircleAll (location, radius);
                     foreach (Collider2D col in objectsInRange) {
                         EnemyScript enemy = col.GetComponent<EnemyScript> ();
                         if (enemy != null) { // linear falloff of effect float proximity = (location - enemy.transform.position).magnitude; float effect = 1 - (proximity / radius); enemy.ApplyDamage(damage * effect);
                             if (shot.gameObject != null) {
                                 Destroy(shot.gameObject);
                             }
                             damage = shot.damage;
                             GetComponent<HealthScript>().ApplyDamage();
                         }
                     }
                 }
             }
         }
     }
 }



Sorry for bad english, thank in advance

Comment
Add comment · Show 1
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 WhiteDevil197 · May 21, 2015 at 06:47 AM 0
Share

i tried replacing line 52 in shotdetection by col.GetComponent().ApplyDamage(); but it didn't seem to work either.

Using the debug mode, i saw that damage value always was reset to 0. I tried to move it in different place but it didn't work neither. only the shot and the collided gameobject were destroyed.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by WhiteDevil197 · May 21, 2015 at 09:35 AM

By debugging myself, i resolved the first problem by replacing line 52 by col.GetComponent().ApplyDamage(); Now i face a second problem. The "damage" value always was reset to 0. I tried moving it out of the foreach, but it didn't worked. only the shot and the collided gameobject get destroyed.

EDIT : the problem is in the line 22 of healthscript. The code should search in the collided gameObject and not in the gameobject with his life being substracted. That's why it work only on the collided gameobject. He's the only one to have "ShotDetection" with the right value of damage. Could someone tell me how i should do that pls?

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
avatar image
0

Answer by fafase · May 21, 2015 at 08:19 AM

My two cents, use Physics2D.OverlapCircleAll.

Then you get an array of Collider2D that are inside the circle.

 foreach(Collider2D collider in arrayCollider){
     HelathScript hs = collider.gameObject.GetComponent<HealthScript>();
     if(hs != null){
         hs.ApplyDamage(damage);
     }
 }

You would be better off passing how much damage you want to apply instead of going backward trying to access back the script as you do to get the damage value.

Once you get that working, you can get to the next step by calculating the distance between the center of the explosion and the current object.

 float distance = Vector3.Distance(centerPointcollider.gameObject.transform.position);
 float damage = 1 / Mathf.Sqr(distance) * initialDamage;

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.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

Health Code, Damage and Healing 0 Answers

unity health bar not losing health 1 Answer

Implementing Damage to Gun, best way to implement health and damage. 1 Answer

How to make heart health system? 3 Answers

Enemies sharing health 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges