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 nicmarxp · Mar 07, 2019 at 05:27 PM · eventdelegate

How do convert a lambda event subscription to be able to unsubscribe it?

I'm very new to events/delegates so sorry if I use the incorrect terminology.

I'm using an inventory script for Unity, that uses C# events/delegates to subscribe to a right click event on an item slot.

The problem is when I dynamically add new item slots, I need to add the event handlers to the new slots. If I just run UpdateEvents(), the ones that were there in the first place, now has duplicate triggers.

The current code is using a lambda syntax, and I've studied these threads on how to create a delegate instance:

  • https://stackoverflow.com/questions/805829/how-to-unsubscribe-from-an-event-which-uses-a-lambda-expression

  • https://stackoverflow.com/questions/10933328/unsubscribing-from-anonymous-delegate-event

Here's the original lambda subscription:

 // This is the lambda expression that I want to unsubscribe to
 ItemSlots[i].OnRightClickEvent += slot => EventHelper(slot, OnRightClickEvent);


Here's what I tried, and I marked with ** on the parts that my IDE highlights as wrong:

 // Try 1
 EventHandler lambda = slot => EventHelper(slot, OnRightClickEvent);
 ItemSlots[i].OnRightClickEvent += lambda;
 
 // Try 2
 EventHandler handler = (sender, e) => EventHelper(sender, OnRightClickEvent);
 ItemSlots[i].OnRightClickEvent += handler;

 // Try 3    
 var myDelegate = delegate(sender, e) { EventHelper(**e**, OnRightClickEvent); };
 ItemSlots[i].OnRightClickEvent += myDelegate;


I also tried converting it without using lambda, but it doesn't work like it should. I'm not sure what "slot" refers to in the lambda. Is it the instance triggering the event? Here's what didn't work, but didn't give any errors:

 // Try without lambda
 ItemSlots[i].OnRightClickEvent         += OnRightClickEvent;


Here's a shortened version of the complete code. I don't fully understand how the EventHelper()-method works, but it seems to be some shortcut to check for null.

 using System;
 using System.Collections.Generic;
 using UnityEngine;
 
 public abstract class ItemContainer : MonoBehaviour, IItemContainer {
     public List<ItemSlot> ItemSlots;
 
     // There are really 8 event here, but I simplified it
     public event Action<BaseItemSlot> OnRightClickEvent;
 
     protected virtual void Awake() {
         UpdateEvents();
         SetStartingItems();
     }
 
     public virtual void UpdateEvents() {
         for (int i = 0; i < ItemSlots.Count; i++) {
             // This is the lambda expression that I want to unsubscribe to
             ItemSlots[i].OnRightClickEvent += slot => EventHelper(slot, OnRightClickEvent);
         }
     }
 
     private void EventHelper(BaseItemSlot itemSlot, Action<BaseItemSlot> action) {
         if (action != null)
             action(itemSlot);
     }
 }

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 mchts · Mar 07, 2019 at 06:09 PM -1
Share

-= operator unscubscribes where += subscribes

2 Replies

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

Answer by Hellium · Mar 07, 2019 at 06:04 PM

Try this:

  using System;
  using System.Collections.Generic;
  using UnityEngine;
  
  public abstract class ItemContainer : MonoBehaviour, IItemContainer {
      public List<ItemSlot> ItemSlots;
      private List<Action<BaseItemSlot>> listeners = new List<Action<BaseItemSlot>>();
  
      // There are really 8 event here, but I simplified it
      public event Action<BaseItemSlot> OnRightClickEvent;
  
      protected virtual void Awake()
      {
          UpdateEvents();
          SetStartingItems();
      }
  
      public virtual void UpdateEvents()
      {
          for (int i = 0; i < ItemSlots.Count; i++)
          {
              Action<BaseItemSlot> listener = slot => EventHelper(slot, OnRightClickEvent);
              if( listeners.Count <= i )
              {
                 listeners.Add(listener);
              }
              else
              {
                  ItemSlots[i].OnRightClickEvent -= listeners[i];
                  listeners[i] = listener;
              }
              
              ItemSlots[i].OnRightClickEvent += listeners[i];
          }
      }
  
      public virtual void RemoveEvents()
      {         
          for (int i = 0; i < ItemSlots.Count; i++)
              ItemSlots[i].OnRightClickEvent -= listeners[i];
      }
  
      private void EventHelper(BaseItemSlot itemSlot, Action<BaseItemSlot> action)
      {
          if (action != null)
              action(itemSlot);
      }
  }


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 nicmarxp · Mar 07, 2019 at 07:09 PM 0
Share

Thanks a lot! This seems to be very close to what I needed. However when I run UpdateEvents() again, it adds another set of triggers. I noticed the RemoveEvents() method, but it wasn't in use, so I added it to the top of UpdateEvents(), however I got ArgumentOutOfRangeException: Argument is out of range. I tried to put if (listeners.Count > 0 && listeners[i] != null) { inside the for loop (with curly braces of course) but i got an "out of range" error also when adding a new item...

avatar image Hellium nicmarxp · Mar 07, 2019 at 09:00 PM 0
Share

I have updated my answer so as to remove the listener if it has been added beforehand.

avatar image nicmarxp · Mar 07, 2019 at 07:10 PM 0
Share

I'm considering storing the reference inside the ItemSlots[i] object. Not sure if that's a good idea though. :)

avatar image nicmarxp · Mar 07, 2019 at 09:17 PM 0
Share

Thanks, this worked great, and was cleaner that to store the reference in the itemslot. However when I try to add back the other events, I run into a problem.

Should I store one List for each event, like private List> rightClickListeners = new List>(); private List> dragStartListeners = new List>(); ...and so on?

It seems to be so much repeating of code. I accepted your answer though :)

avatar image Hellium nicmarxp · Mar 08, 2019 at 08:26 AM 0
Share

I am sorry, I've tried something but I wasn't able to get a working and clean solution....

Good luck!

avatar image
0

Answer by nicmarxp · Mar 08, 2019 at 09:11 AM

I ended up solving it another way, based on some tips I got from other forums, also on naming the events.

 public event Action<BaseItemSlot> RightButtonClicked;
 public virtual void UpdateEvents() {
     for (int i = 0; i < ItemSlots.Count; i++) {
         // Unsubscribe, subscribe again
         ItemSlots[i].RightButtonClicked -= OnRightButtonClicked;    ItemSlots[i].RightButtonClicked += OnRightButtonClicked;
     }
 }
 private void EventHelper(BaseItemSlot itemSlot, Action<BaseItemSlot> action) {
     if (action != null)
         action(itemSlot);
 }

 private void OnRightButtonClicked(BaseItemSlot slot) {
     EventHelper(slot, RightButtonClicked);
 }

It seems there is no issue unsubscribing something that isn't subscribed, so I always unsubscribe it first. This way I don't have to keep a list of what's going on.

Thanks for your help :)

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

104 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

Related Questions

Delegates versus class references 1 Answer

Event to change level 1 Answer

Login form: Do I have to set custom delegates to null in OnDestroy? 0 Answers

Score system using events to pass data? 1 Answer

custom event delegate - convertible error 3 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