Skip to content

favoyang/unity-action-sender

Repository files navigation

logo

Unity Action Sender

openupm

A type-safe replacement to SendMessage.

SendMessage is a known trap for hard to maintain. An alternative way is leveraging interfaces with GetComponents<T>. This package consists of a group of extension API to simplify the approach.

Notice that Unity EventSystems uses the same approach to support custom message. The major difference is that Unity EventSystems is designed for the UI system, therefore it takes extra efforts to support consume, use, or reset an event (like clicks). While this package API is more accessible and similar to the SendMessage calls. See more discussion in #1.

How to Use

Define an interface for your callbacks.

public interface IDamageable
{
    void Damage(float amount);
    bool IsAlive();
}

Implements the interface on your component.

public class Unit : MonoBehaviour, IDamageable
{
    public void Damage(float amount)
    {
      // take damage.
    }

    public bool IsAlive()
    {
      // return is alive?
    }
}

Import the namespace to send actions.

using LittleBigFun.ActionSender;

Replace SendMessage with:

gameObject.SendAction<IDamageable>(t => t.Damage(1.0f));

Replace BroadcastMessage with:

gameObject.BroadcastAction<IDamageable>(t => t.Damage(1.0f));

Replace SendMessageUpwards with:

gameObject.SendActionUpwards<IDamageable>(t => t.Damage(1.0f));

To get result value of actions:

var results = gameObject.SendAction<IDamageable, bool>(t => t.IsAlive());
var results = gameObject.BroadcastAction<IDamageable, bool>(t => t.IsAlive());
var results = gameObject.SendActionUpwards<IDamageable, bool>(t => t.IsAlive());

Install Package

The package is available on the openupm registry. It's recommended to install it via openupm-cli.

openupm add com.littlebigfun.action-sender

Or you can install via Git URL.

Media

Icons made by Freepik from flaticon.com


License: see LICENSE.md

About

A type-safe replacement to SendMessage.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages