If I would name two things that helps me to keep my code readable and well organized, it will be interfaces and Zenject.
Today I had an idea, that it would be nice, if obstacles in my game somehow stopped after hero passes through them. So they should gradually stop moving, stop rotating, shadow offset should decrease to zero to make a “landing effect” and maybe they could became a bit darken.
I have made an interface like this:
public interface IStoppable
{
void Stop();
void Run();
}
and made my Rotator, Mover, Colorizer and ShadowCaster classes implement it. Now I made a Stopper class, like this:
public class Stopper : MonoBehaviour, IHandleMessage<LevelStateChangedMessage>
{
private IEnumerable<IStoppable> stoppables;
public void Handle(LevelStateChangedMessage message)
{
if (message.LevelState == LevelState.Reseted)
{
foreach (var stoppable in stoppables)
{
stoppable.Run();
}
}
}
private void Start()
{
stoppables = GetComponentsInChildren<IStoppable>();
}
[Inject]
public void Construct(IMessenger messenger)
{
messenger.Subscribe(this);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag(ObjectNames.Hero))
{
foreach (var stoppable in stoppables)
{
stoppable.Stop();
}
}
}
}
And that’s it. In case that hero passes collider behind the obstacles everything that that is stoppable will stop.
And Zenject? When I was implementing IStoppable on my ShadowCaster class, I wanted shadow to disapear gradually, so ShadowCaster now needs to know what time is it. I have added this line:
[Inject] private ILevelTimeProvider levelTimeProvider;
Just this line is enough and now I can anywhere within ShadowCaster class use
var time = levelTimeProvider.Time;
to get level time.
And when I am looking at the Stopper class, there is also third tool that helps me a lot. It is event aggregator pattern (in my implementation called IMessanger). Stopper needs to now when the level is reseted, so he can restart all the obstacles and I think that role of IMessenger in this is pretty self-explanatory.
Without these “tools” I would not be able to finish a project. They allow me to focus just on the one class I am currently working on and I don’t have to think about anything else.