Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
1
Question by Joe Long · Jun 30, 2015 at 12:17 PM · scripting problemdestroygameobjectshieldstatic variables

Multiple GameObjects accessing the same script, when script destroys game object, it destroys it across all the GameObjects

I'm making a shield system for the enemy ships. I have all of the shields running off of the same shield script, which seems to work fine other than when it destroys the game object. All of the ships take getting the shield hit fine and plays corresponding animation for the shield hit and decrements the shield health separately from each other but when i destroy one of the shields, all of the shields get destroyed. It could be a simple mistake because I'm a noob at coding and Unity but any help would be so greatly appreciated.

Here is the code that runs the shields:

     public float shield = 100f;
     private Animator anim;
     //this variable tells the enemy collider to not collide with projectile if the shield is still up
     public static bool shieldDestroyed;
 
     void Start() {
         anim = GetComponent<Animator> ();
         shieldDestroyed = false;
     }
     
     void OnTriggerEnter2D (Collider2D col) {
         Projectile missile = col.gameObject.GetComponent<Projectile> ();
         
         if (missile != null) {
             shield -= missile.GetDamage ();
             missile.Hit ();
             anim.Play ("ShieldHit");
             if (shield <= 0) {
                 shieldDestroyed = true;
                 StartCoroutine(Shield());
             }
         }
     }
     
     IEnumerator Shield () {
         if (shield <= 0) {
             anim.Play ("ShieldDown");
             yield return new WaitForSeconds (0.06f);
             Destroy (gameObject);
         }
     }
 
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

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by RSoj · Jun 30, 2015 at 12:49 PM

There is a problem with the shieldDestroyed variable. If you declare it with 'static' as so, it has same value for all of the Shield instances. So if one shield is destroyed by line 19., every other shield are also inactive having shieldDestroyed equal true.

So I assume your other shields are not Destroy from line 29., they are just inactive. Is it so?

Remove the 'static' keyword and it should work.

Edit according to comment:

OK, it is still the same issue. You cannot use static variables - the static makes it same value for all your objects, but you need every object to have its own value. It is mandatory to understand the difference.

I understand why you made it static in first place - you need to access Enemy values from Shield and vice versa. But you need to use reference to the objects, not the class itself. You already have it done right with the Projectile.

So now how to make it work - you have reference to the shield object on line 1 in Enemy, then you make a new instance of the shield on line 10. The 'shield1' is exactly you need to use. Assign the 'shield1' to field e.g. 'shieldInstance' which you declare under line 1. Then everytime you need to check something within the shield, use this variable.

EnemyBehaviour:

  public GameObject enemyShield;
  private GameObject shieldInstance;
  public static float shield;
  public float shieldHealth;
  private bool shieldDown = false;
 
  void Start(){
      Vector3 offsetY = new Vector3 (transform.position.x, transform.position.y - 0.2f);
      shieldInstance = (GameObject) Instantiate (enemyShield, offsetY, enemyShield.transform.rotation);
      shieldInstance.transform.parent = transform;
      shield = shieldHealth;
  }
 
  void Update () {
 
      if (shieldInstance.GetComponent<EnemyShield>().shieldDestroyed == true) {
          shieldDown = true;
      } else {
          shieldDown = false;
      }
 
  }
 
  void OnTriggerEnter2D (Collider2D col) {
 
      Projectile missile = col.gameObject.GetComponent<Projectile> ();
 
      if (missile != null & shieldDown == true) {
          health -= missile.GetDamage ();
          missile.Hit ();
      }
      if (health <= 0) {
          Destroy (gameObject);
      }
  }

Shield:

 private Animator anim;
  //this variable tells the enemy collider to not collide with projectile if the shield is still up
  public bool shieldDestroyed;
  private float shieldHealth;
 
  void Start() {
      anim = GetComponent<Animator> ();
      shieldDestroyed = false;
      shieldHealth = EnemyBehaviour.shield; 
  }
 
  void Update () {
      if (shieldHealth <= 0) {
          shieldDestroyed = true;
      } else {
          shieldDestroyed = false;
      }
 
 
  } 
 
  void OnTriggerEnter2D (Collider2D col) {
      Projectile missile = col.gameObject.GetComponent<Projectile> ();
      
      if (missile != null) {
          shieldHealth -= missile.GetDamage ();
          missile.Hit ();
          anim.Play ("ShieldHit");
          if (shieldHealth <= 0) {
              shieldDestroyed = true;
              anim.Play ("ShieldDown");
              Destroy (gameObject, 0.08f);
 
          }
      }
  }

It will need some performance refactoring obviously, but it is important to understand the concept.

Comment
Add comment · Show 4 · 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 Joe Long · Jun 30, 2015 at 05:37 PM 0
Share

Yes this is so. The reason I'm using the static keyword is so that i can call it from my enemy class. I check that the shield has been destroyed in the enemy collider so that the projectile does not accidentally collide with the enemy ship before the shield is down. Last night I figured out how to fix the earlier problem was to update the shieldDestroyed variable in the update function but this just caused another bug that now i have to destroy all the shields before I can destroy the enemy ship. I know that it has to do with the 'if' statement checking if the shield is down before it collides but I just don't know how to fix it.

Heres the code for my enemy class:

     public GameObject enemyShield;
     public static float shield;
     public float shieldHealth;
     private bool shieldDown = false;
 
 
 
     void Start(){
         Vector3 offsetY = new Vector3 (transform.position.x, transform.position.y - 0.2f);
         GameObject shield1 = (GameObject) Instantiate (enemyShield, offsetY, enemyShield.transform.rotation);
         shield1.transform.parent = transform;
         shield = shieldHealth;
 
 
     }
 
     void Update () {
 
         if (EnemyShield.shieldDestroyed == true) {
             shieldDown = true;
         } else {
             shieldDown = false;
         }
 
     }
 
     void OnTriggerEnter2D (Collider2D col) {
 
         Projectile missile = col.gameObject.GetComponent<Projectile> ();
 
         if (missile != null & shieldDown == true) {
             health -= missile.GetDamage ();
             missile.Hit ();
         }
         if (health <= 0) {
             Destroy (gameObject);
             
         }
 
     }

Ane here is how I have the shield class now:

     private Animator anim;
     //this variable tells the enemy collider to not collide with projectile if the shield is still up
     public static bool shieldDestroyed;
     private float shieldHealth;
 
 
     void Start() {
         anim = GetComponent<Animator> ();
         shieldDestroyed = false;
         shieldHealth = EnemyBehaviour.shield; 
     }
 
     void Update () {
         if (shieldHealth <= 0) {
             shieldDestroyed = true;
         } else {
             shieldDestroyed = false;
         }
 
 
     } 
 
     void OnTriggerEnter2D (Collider2D col) {
         Projectile missile = col.gameObject.GetComponent<Projectile> ();
         
         if (missile != null) {
             shieldHealth -= missile.GetDamage ();
             missile.Hit ();
             anim.Play ("ShieldHit");
             if (shieldHealth <= 0) {
                 shieldDestroyed = true;
                 anim.Play ("ShieldDown");
                 Destroy (gameObject, 0.08f);
 
             }
         }
     }
     
avatar image Joe Long · Jun 30, 2015 at 06:54 PM 1
Share

You are a life saver, thank you so much. I'm still new at this so thank you for the knowledge! if you wouldn't $$anonymous$$d me asking how would i go about doing performance refactoring

avatar image RSoj · Jun 30, 2015 at 07:08 PM 0
Share

You're welcome! For the basic refactoring - firstly look for expensive things that are happening every frame. In this case it is EnemyBehaviour line 16. You can hold reference directly to the EnemyShield component, ins$$anonymous$$d of getting it every time.

 private EnemyShield shieldInstanceComponent;
 ...
 shieldInstance = (GameObject) Instantiate (enemyShield, offsetY, enemyShield.transform.rotation);
 shieldInstance.transform.parent = transform;
 shieldInstanceComponent = shieldInstance.GetComponent<EnemyShield>();
 ...
 if (shieldInstanceComponent.shieldDestroyed) {
    shieldDown = true;
 } else {
    shieldDown = false;
 }

Secondly there is no longer need to check if shieldHealth <= 0 every frame (in EnemyShield), it is already handled on line 29 after collision.

avatar image Joe Long · Jul 01, 2015 at 06:29 AM 0
Share

$$anonymous$$uch thanks again RSoj! I've been going through my code and refactoring now

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

NPC movement 1 Answer

Parallax not working C# 0 Answers

Destroying upon collision 1 Answer

If renderer.material.color help!??!?!!? 1 Answer

Treasure Magnet HELP!! 1 Answer


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