Skip to content

Instantly share code, notes, and snippets.

@chrisyarbrough
Created February 12, 2021 17:38
Show Gist options
  • Select an option

  • Save chrisyarbrough/d20bbbc0419198ffb7b24448f7bc983d to your computer and use it in GitHub Desktop.

Select an option

Save chrisyarbrough/d20bbbc0419198ffb7b24448f7bc983d to your computer and use it in GitHub Desktop.
Be careful when refactoring lambdas with method groups. The method group may seem cleaner but it also breaks virtual methods by only calling the base implementation.
using System;
using DG.Tweening;
using Nementic.Exit;
using UnityEngine;
public class VirtualDelegateInvocation : MonoBehaviour
{
private Child p = new Child();
[EditorButton()]
void Do()
{
p.Close();
}
}
public class Parent
{
public void Close()
{
// Close instantly:
//OnClose();
// Or defer to later:
var sequence = DOTween.Sequence();
sequence.AppendInterval(1f);
sequence.onComplete += OnClose;
// So far this works.
// Refactor:
Do(OnClose);
}
private void Do(Action callback)
{
var sequence = DOTween.Sequence();
sequence.AppendInterval(1f);
// Child and base implementations are called.
sequence.onComplete += () => callback();
// Ups, broken, only the base class is called.
sequence.onComplete += callback.Invoke;
}
protected virtual void OnClose()
{
Debug.Log("Base");
}
}
public class Child : Parent
{
protected override void OnClose()
{
Debug.Log("Child");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment