Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler Warning CS0067 : The event is never used

Tags:

c#

events

I have an event that I am using, so I don't really understand what this warning really means. Can someone clarify?

public abstract class Actor<T> : Visual<T> where T : ActorDescription
{
    #region Events
    /// <summary>
    /// Event occurs when the actor is dead
    /// </summary>
    public event Action Dead;
    #endregion

/// <summary>
    /// Take damage if the actor hasn't taken damage within a time limit
    /// </summary>
    /// <param name="damage">amount of damage</param>
    public void TakeDamage(int damage)
    {
        if (damage > 0 && Time.time > m_LastHitTimer + m_DamageHitDelay)
        {
            m_CurrentHealth -= damage;

            if (m_CurrentHealth <= 0)
            {
                m_CurrentHealth = 0;

                if (Dead != null)
                    Dead();
            }
            else
                StartCoroutine(TakeDamageOnSprite());

            m_LastHitTimer = Time.time;
        }
    }

In my other class, I register and unregister for the event:

        if (m_Player != null)
            m_Player.Dead += OnPlayerDead;

        if (m_Player != null)
            m_Player.Dead -= OnPlayerDead;
like image 618
Hector Llanos Avatar asked Apr 13 '15 01:04

Hector Llanos


2 Answers

Since the class Actor<T> is abstract, and no code inside Actor<T> raises the event, you can make the event abstract:

public abstract event Action Dead;

Then in subclass(es) which inherit from Actor<T>, you override the event:

public override event Action Dead;

If a subclass doesn't actually raise the event, then you can suppress the warning by giving the event empty add and remove methods (see this blog post).

public override event Action Dead
{
    add { }
    remove { }
}
like image 159
Blorgbeard Avatar answered Oct 08 '22 06:10

Blorgbeard


The real problem is that I am using Unity and Mono 2.6 and its still a bug. Therefore, I attempted to use the suggestion that Blorgbeard said, however; it worked for Visual Studio but not for the compiler.

So there are two solutions throwing #pragma warning disable around the event, or passing the generic type.

like so:

public abstract class Actor<T> : Visual<T> where T : ActorDescription
{
    #region Events
    /// <summary>
    /// Event occurs when the actor is dead
    /// </summary>
    public event Action<Actor<T>> Dead;
    #endregion

    ...

    private void SomeFunc()
    {
        if (Dead != null)
            Dead();
    }
}
like image 31
Hector Llanos Avatar answered Oct 08 '22 05:10

Hector Llanos