Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 kbkmn · Dec 27, 2019 at 10:10 AM · patterndestruction

Projectile destruction with Observer pattern

I've build a little prototype game. Each player can shoot projectile and can't shoot again until it explodes (out of screen bounds, collision, etc). I'm using Observer pattern so player subscribes to projectile instance destruction delegate and changes its state when projectile destroyed. My question is: how do i unsubscribe from projectile that being destroyed?

 public class Projectile : MonoBehaviour
 {
     [SerializeField] private float _speed = 5f;
     private Rigidbody2D _rigidbody2D;
     public event Action OnDestroy;
 
     private void Awake()
     {
         _rigidbody2D = GetComponent<Rigidbody2D>();
     }
 
     private void FixedUpdate()
     {
         _rigidbody2D.MovePosition(_rigidbody2D.position + (Vector2)_rigidbody2D.transform.up * _speed * Time.fixedDeltaTime);
     }
 
     private void OnBecameInvisible()
     {
         OnDestroy?.Invoke();
         
         Destroy(gameObject);
     }
 }
 
 public class Player : MonoBehaviour
 {
     [SerializeField] private Projectile _projectilePrefab;
 
     private bool _canShoot = true;
 
     private void Update()
     {
         ShootHandler();
     }
 
     private void ShootHandler()
     {
         if (_canShoot == false)
             return;
 
         if (Input.GetButtonDown(KeyCode.Space)) {
             _canShoot = false;
 
             Projectile projectile = Instantiate(_projectilePrefab, transform.position, Quaternion.identity);
             projectile.OnDestroy += ProjectileDestoyed;
         }
     }
 
     private void ProjectileDestoyed()
     {
         _canShoot = true;
     }
 }
Comment
Add comment · Show 4
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 NorthStar79 · Dec 27, 2019 at 10:18 AM 0
Share
 private void ProjectileDestoyed()
      {
          projectile.OnDestroy -= ProjectileDestoyed;
          _canShoot = true;
      }

isn't this working?

avatar image kbkmn NorthStar79 · Dec 27, 2019 at 10:27 AM 0
Share

there is no projectile in ProjectileDestoyed function scope and it seems redundant to store projectile reference in player instance

avatar image NorthStar79 kbkmn · Dec 27, 2019 at 11:00 AM 1
Share

What about returning the projectile object with event if you don't want to cache it.

something like this :

 private void ProjectileDestoyed(projectile myProjectile)
       {
           myProjectile.OnDestroy -= ProjectileDestoyed;
           _canShoot = true;
       }
Show more comments

1 Reply

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

Answer by Hellium · Dec 27, 2019 at 10:52 AM

You don't really need to unsubscribe to the event, because the projectile object has been destroyed. You would need to unsubscribe to the event if the lifetime of the player was shorter than the lifetime of the projectile, but it does not seem to be the case.


Anyway, if you really want to, here is how you could do it:

 public class Projectile : MonoBehaviour
  {
      [SerializeField] private float _speed = 5f;
      private Rigidbody2D _rigidbody2D;
 
      // OnDestroy is a function of Unity, you may have problems
      // And I personally name my events with a past-tense verb
      // meaning something has occured.
      public event Action<Projectile> Destroyed;
  
      // ...
      private void OnBecameInvisible()
      {
          Destroyed?.Invoke(this);
          
          Destroy(gameObject);
      }
  }
  
  public class Player : MonoBehaviour
  {
      [SerializeField] private Projectile _projectilePrefab;
  
      private bool _canShoot = true;
  
      private void Update()
      {
          ShootHandler();
      }
  
      private void ShootHandler()
      {
          if (_canShoot == false)
              return;
  
          if (Input.GetButtonDown(KeyCode.Space)) {
              _canShoot = false;
  
              Projectile projectile = Instantiate(_projectilePrefab, transform.position, Quaternion.identity);
              projectile.Destroyed += ProjectileDestoyed;
          }
      }
  
      private void ProjectileDestoyed(Projectile destroyedProjectile)
      {
          destroyedProjectile.Destroyed  -= ProjectileDestoyed;
          _canShoot = true;
      }
  }

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 kbkmn · Dec 27, 2019 at 11:55 AM 0
Share

It works, but code seems weird somehow. Unsubscription needed for garbage collection.

avatar image Hellium kbkmn · Dec 27, 2019 at 12:01 PM 0
Share

Why do you think the code is weird?


When the object is destroyed, the event is destroyed to and the event callbacks are automatically removed and disposed so you don't have to worry.

avatar image kbkmn Hellium · Dec 27, 2019 at 01:43 PM 0
Share

I don't know. I guess its use of instance inside delegate of the same instance looks strange to me. I'll get used to things like this

Show more comments

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

118 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

Related Questions

How can Unity framework recognize the functions defined in child objects? 1 Answer

Lighting cubic patterns problem 0 Answers

How to spawn a random hexagon pattern? 0 Answers

Render material only when in front of specific objects 0 Answers

How do you make an algebra function for this pattern? 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