Jump to content
Sign in to follow this  
  • entry
    1
  • comment
    1
  • views
    388

Components and Messages in Unity

Sign in to follow this  
nbrosz

902 views

Up to now, I have had a tendency toward monolithic classes when developing in Unity. My experience has always been with the typical object-oriented approach (with the exception of when I was developing using batari Basic), but I’ve been trying to train myself toward small, reusable components with focused purposes. I’ve had some good success lately, breaking larger scripts into smaller ones and using interfaces as a means of communicating between components where possible.

public class ReportAttack : MonoBehaviour, IDamageable {
    public Team team;
    void Start () {
		team = GetComponent<Team>();
	}

    void IDamageable.TakeDamage(MonoBehaviour from, DamageType type, float amount)
    {
		var attackerTeam = from.GetComponent<Team>();
		if (team && attackerTeam && team.team != attackerTeam.team)
			Debug.Log(gameObject.name + " says: I've Been Attacked by " + from.gameObject + " on team " + (attackerTeam ? attackerTeam.team.ToString() : "no team") + " with " + System.Enum.GetName(typeof(DamageType), (DamageType)((int)type << 1)) + " (" + (int)type + ")");
    }
}

While I’ve been fairly satisfied with the use of interfaces for calls to multiple or unknown components, I recall fondly the rapid development and flexible approach provided by utilizing messages in my 2017 Global Game Jam submission, Metalmancer.


However, since Unity’s message passing uses reflection (or at least probably does, given that it takes the string name of the event to call), it does not perform particularly well. With that in mind, I hoped to make my own, alternative messaging system which is used much like the existing messaging system, but uses delegates and event handlers under the hood. This was the result.


While I felt that I succeeded in my goal of providing a useful interface that hid the reflection-based old messaging system, I was crestfallen once I began running tests. Performance Testing On average, I see a performance increase of about 33% over Unity’s built in SendMessage, with the complication that all components using the new system must inherit from the new MessagingBehavior abstract class, rather than directly from MonoBehavior. Still, given that a direct call (as would be the case using an interface) is still about ten times faster, I wasn’t particularly encouraged by these results.

On the other hand, as tomvds said in the Unity forums:

Optimization is not about avoiding expensive code. It’s about avoiding expensive code where it matters.

Performance Testing Still, stubborn as I am, it’ll be hard to convince myself to use even my own message passing architecture in lieu of more efficient interfaces. Or maybe I should just use an adaptation of wmiller’s Events system. Or I should just stop worrying about it.


View the full article

Sign in to follow this  


1 Comment


Recommended Comments

I do wish Unity had a better model for events built-in.  Having to use strings is error prone and cumbersome.  

Have you looked a UniRX at all?  I'd be curious to see how it compares with your other numbers.

Edited by ferrous

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By Rio Lloyd
      Hey all!
      we are a team of 3 looking for more members, 
      we are making an isometrical Survival RPG.
      we are looking For Members who can make low poly 3D artists who can do character models, environments, tools and more.
       
      if interested and want to know more email me at rioishere14@gmail.com
    • By Adeilton Alves
      Hello everyone, I'm new here and sorry if this isn't the right place to ask but i asked in a few forums around the internet and no one yet help with it.. I'm have been trying to mod this game for years, but I still stuck with the raw files from RACJIN games, 
      Raw Files [ Mod edit: Removed ]
      I would like to identify the compression algorithm used to compress these files so that they can be decompressed and analyzed.

      Game : Naruto Uzumaki Chronicles 2... A.K.A Naruto Konoha Spirits in Japan.
    • By nxrighthere
      BenchmarkNet is a console application for testing the reliable UDP networking solutions.
      Features:
      Asynchronous simulation of a large number of clients Stable under high loads Simple and flexible simulation setup Detailed session information Multi-process instances Supported networking libraries:
      ENet UNet LiteNetLib Lidgren MiniUDP Hazel Photon Neutrino DarkRift More information and source code on GitHub.
      You can find the latest benchmark results on the wiki page.
       
    • By trapazza
      I'm trying to add some details like grass, rocks, trees, etc. to my little procedurally-generated planet. The meshes for the terrain are created from a spherified cube which is split in chunks (chunked LOD).
      To do this I've wrote a geometry shader that takes a mesh as input and uses its vertex positions as locations where the patches of grass will be placed (as textured quads).
      For an infinite flat world (not spherical) I'd use the terrain mesh as input to the geometry shader, but I've found that this won't work well on a sphere, since the vertex density is not homogeneous across the surface.
      So the main question would be: How to create a point cloud for each terrain chunk whose points were equally distributed across the chunk?
      Note: I've seen some examples where these points are calculated from intersecting a massive rain of totally random perpendicular rays from above... but I found this solution overkill, to say the least.
      Another related question would be: Is there something better/faster than the geometry shader approach, maybe using compute shaders and instancing?
    • By FedGuard
      Hello all,
       
      I would like to start off with thanking you all for this community. Without fora like these to assist people the already hard journey to making an own game would be exponentially more difficult. Next I would like to apologize for the long post, in advance...
      I am contemplating making a game. There, now that's out of the way, maybe some further details might be handy.
      I am not some youngster (no offence) with dreams of breaking into the industry, I am 38, have a full-time job, a wife, kid and dog so I think I am not even considered indie? However I recently found myself with additional time on my hands and decided I would try my hand at making a game.Why? Well mostly because I would like to contribute something, also because I think I have a project worth making (and of course some extra income wouldn't hurt either to be honest). The first thing I realized was, I have absolutely no relevant skill or experience. Hmm; ok, never mind, we can overcome that, right?
      I have spent a few months "researching",meaning looking at YouTube channels, reading articles and fora. Needless to say, I am more confused now than when I started. I also bought some courses (Blender, Unity, C#) and set out to make my ideas more concrete.
      I quickly discovered, I am definitely not an artist... So I decided, though I do plan to continue learning the art side eventually, I would focus on the design and development phase first. The idea being, if it takes me a year or more solely learning stuff and taking courses without actually working on my game, I would become demoralized and the risk of quitting would increase.
      So I thought I would:
      1: Keep following the courses Unity and C# while starting on the actual game development as the courses and my knowledge progress.
      2: Acquire some artwork to help me get a connection with the game and main character, and have something to helm keep me motivated. (I already did some contacting and realized this will not be cheap...). Also try to have the main character model so I can use it to start testing the initial character and game mechanics. For this I have my first concrete question. I already learned that outsourcing this will easily run up in the high hundreds or thousands of dollars... (lowest offer so far being 220 USD) I am therefore playing with the idea of purchasing https://assetstore.unity.com/packages/3d/animations/medieval-animations-mega-pack-12141 with the intention of then have an artist alter and/or add to the animations (it is for a Roman character so some shield animations are not going to work the same way.). This way I could start  with the basic character mechanics. Is this a good idea, waste of money,...? Any suggestions? I then have a related but separate question. Is it a good idea to buy Playmaker (or some other similar software I haven't yet heard of like RPGAIO), and using this for initial build, then changing/adding code as the need arises?
      3.Get a playable initial level ready as a rough demo and then starting to look for artist for level design and character/prop creation.
      ...
       
      I would really appreciate some input from more experienced people, and especially answers to my questions. Of course any advice is extremely welcome.
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!