Unity 3D: Event Exercise

Опубликовано: 25 Апрель 2026
на канале: Why485
1,101
22

I’ve been wanting to practice with events for a while now to help reduce my tendency for hard coded inter-dependency of components in Unity, so yesterday I wrote a simple gun. As part of the exercise I also wanted to try and separate out as many things in different components as possible because I have a bad habit of writing giant mega components that do everything.

The bullet consists of a Projectile, Movement, and Explosion components. The gun itself has a Gun, shell ejector, and muzzle flash component. I used to handle all these things in one bullet or gun component each, but that tended to get very crowded and I never liked how it kind of goes against how Unity is designed to work.

Now, when the gun fires it calls an OnWeaponFired event. The muzzle flash and shell ejector are registered to this event. The gun itself spawns a bullet and calls the OnBulletFired event on the bullet which the movement is registered to. When the bullet times out, it calls an OnBulletDestroy event where the explosion component generates the explosion.

This is all with vanilla C# stuff, not the Unity event system.