Sprite Trails Renderer

Just finished a sprite trail renderer project thats free to use. Its available as a unity package on itch. It makes it really easy to create cool sprite trail effects by just adding the Sprite Trail Renderer component to your gameobject! Try it out below.

Instructions
1. Import the SpriteTrailRendererPackage into your project.

2. Add the Sprite Trail Renderer component to your sprite gameobject

3. That’s it! Tweak the settings to create something you like

Making an Object Pool in Unity

If you have a game and you create and destroy GameObjects at a very high frequency and you notice performance going down then maybe you should consider using an object pool.

Today we’ll go over an implementation for an object pool to be used in Unity. You’ll be able to use this class to create pools of any type of GameObject, from pools of bullets to enemies, or environment objects.

Reasoning Behind An Object Pool

The reasoning behind this pattern is to improve performance by removing the need for instantiating and destroying game objects at a high frequency. Though this comes at the expense of memory.

Pattern

The pattern works this way. You pre initialize and create a pool of objects to be used. Whenever you need an object you ask the pool to lend you one. When the object is done serving its purpose instead of destroying it you place it back into the pool to be reused in the future.

When should you use pools?

  • When objects frequently get created and destroyed. Think about particles in a particle system, or bullets in a bullet hell shooter game.
  • When creating an object is really expensive.

Pattern Limitations

There is a tradeoff in using this pattern. One of the big ones is memory. Objects in a pool will take up space in memory whether or not they’re being used. Some objects in a pool may also be unnecessary so it’s a good idea to fine tune your pool to only hold the maximum number of objects to be used concurrently.

Pattern Implementation Ideas

There are a number of implementation details to figure out first. Here’s a couple

  • Should an object know that it’s part of a pool?
    One way to implement a pool is for a pool to continuously check up on individual objects. When one is not in use it can then be reclaimed. But this seems like a little too much work for the pool. The pools job should only be to lend out objects to whoever needs them. But what if the objects know that they’re part of a pool?
  • How should a game object be put back in a pool. From within the pool or outside

As we build our object pool we’ll answer these questions.

So once you’re done what can you expect? Well, you’ll be able to create any type of object pool with a line or 2 of code, as long as the object is a Unity GameObject.

Object Pool Code

Lets start to create our object pool. Lets also decide on a couple things about our pool.

  1. First our pool will be a generic pool as long as the object inherits from MonoBehaviour
  2. Pool objects should have a method used to place themselves back into the pool (move the burden away from the ObjectPool)

Lets create the IPoolable interface that Objects will need to follow if they’re going to be pool objects. This function will be used to set a delegate that’ll be called when the object is done being used. Skip to the bottom for an example and a quickstart on how to make and use this pool object implementation.

IPool Interface Code

public delegate void ReturnObjectToPool(GameObject objectToReturn);

public interface IPoolable
{
    void SetReturnToPool(ReturnObjectToPool returnDelegate);
}

Next lets create the ObjectPool.

using System.Collections.Generic;
using UnityEngine;

public class ObjectPool<T> where T : MonoBehaviour, IPoolable
{
    private Stack<T> _objectsNotInUse;
    private int _numberOfObjectsToSpawnWhenEmpty;
    private GameObject _objectPrototype;

    public ObjectPool(GameObject _objectPrototype, int startingNumberOfObjects, int numberOfObjectsToAddWhenEmpty)
    {
        _objectPrototype = _objectPrototype;

        _numberOfObjectsToSpawnWhenEmpty = numberOfObjectsToAddWhenEmpty;
        _objectsNotInUse = new Stack<T>(numberOfObjectsToSpawn);

        AddObjectsToPool(numberOfObjectsToSpawn);
    }

    public void HandleReturnToPool(GameObject objectToReturn)
    {
        objectToReturn.SetActive(false);
        _objectsNotInUse.Push(objectToReturn.GetComponent<T>());
    }

    public T GetObjectFromPool()
    {
        if (_objectsNotInUse.Count == 0)
        {
            AddObjectsToPool(_numberOfObjectsToSpawnWhenEmpty);
        }

        T projectileToReturn = _objectsNotInUse.Pop();
        projectileToReturn.gameObject.SetActive(true);
        return projectileToReturn;
    }

    private void AddObjectsToPool(int amountToAdd)
    {
        for (int i = 0; i < amountToAdd; i++)
        {
            GameObject newGameObject = Object.Instantiate(_objectPrototype, Vector3.zero, Quaternion.identity);
            T poolObject = newGameObject.GetComponent<T>();
            poolObject.SetReturnToPool(HandleReturnToPool);
            _objectsNotInUse.Push(poolObject);

            // turn game object off
            newGameObject.SetActive(false);
        }
    }
}

Example of Using the Object Pool Class

Once you have written or copied these scripts you can use the example below as a quickstart. First declare and instantiate a PoolObject with the 3 parameters.

  1. A GameObject prefab to create a pool out of
  2. An integer for the start number of objects
  3. An integer for the number of objects to add to the pool once the pool is empty (You can fine tune both these ints for your specific pool)

Down below we have the BadGuySpawner that creates the pool and further down we have the BadGuy script that we will be making a pool out of. Note that you only really need the GetObjectFromPool method and the constructor to get started!

using UnityEngine;

public class BadGuySpawner : MonoBehaviour
{
    public GameObject _badGuyPrefab;
    private ObjectPool<BadGuy> _enemyPool;

    private void Start()
    {
        // instantiate an object pool with a start size of 10
        _enemyPool = new ObjectPool<BadGuy>(_badGuyPrefab, 10, 2);
    }

    public void SpawnBadGuy()
    {
        // grab a bad guy from the pool and set default values
        BadGuy badguy = _enemyPool.GetObjectFromPool();
        badGuy.SetDefaultSpawnValues();
    }
}
using UnityEngine;

public class BadGuy : MonoBehaviour, IPoolable
{
    private int _health;
    private ReturnObjectToPool _returnDelegate;    

    private void SetDefaultSpawnValues()()
    {
        _health = 2;
        transform.position = Vector3.zero;
    }

    public void SetReturnToPool(ReturnObjectToPool returnDelegate)
    {
        _returnDelegate = returnDelegate
    }

    public void Die()
    {
        _returnDelegate(gameObject);
    }
}

If you guys use these scripts drop a link to your project down below! Stay tuned for the next post, I’ll go over a new Sprite Trail Renderer asset for 2D games that I’ll be releasing!

Man

Chapter 1

The man woke up with a start. He grabbed the warm sheets and tossed them away from his body, swiveled his legs away from the bed and slowly sat down. He placed his forearms on his thighs. The beads of sweat glimmered from the back of his hands as the dim morning rays pierced into his room.

He looked about. It was a soft white color all around. He faced a flat screen tv sitting on top of a wooden and chestnut colored tv stand. It was around 4 ft across, with 2 small doors in the center. One was partially swiveled open and within you could see a neat stack of books. Peering to his left he saw his closet doors closed shut. With a sigh and a little rub of the eyes he stood and walked over to the bathroom. Here he would start his day, as he did every other day.

The man peered into the mirror. Reflected back he saw his charcoal black hair, and soft dim blue eyes, the kind you see in the early winter morning sky. Low set cheekbones, a sharp jawline, and bags under his eyes, made his eyes appear cold, and sharp.

The man brushed his teeth in circles for 2 minutes, rinsed his brush and entered the shower. He turned on the shower head and used the water to rinse out his mouth. The shower was quick, he dried himself and walked over to his closet.

The man dressed rather plainly, a pair of jeans, a blue long sleeve, and some red vans is all he needed. During this time the sun had come up quite a bit, he opened up the blinds and the sun burst in unimpeded. The man walked over to his satchel, picked it up, and and went out closing the room behind him. Down the stairs he went, 3 floors.

After reaching foot outside he continued on his way. It was the month of May, the sun was bright and the temperature perfect, not to cold not to warm. With the sun behind, his apartment building cast a shadow in front, reaching the building on the opposing side.

The first stop of the day would be his favorite coffee shop, Elis Cafe it was called. He walked to the edge of the block and in the far distance he could see the lumbering giants occupying downtown. He would soon be there for work, but for now, coffee awaited. The man walked 2 blocks soaking in the sun. There was people everywhere. Numbingly he heard the honking of vehicles all about, and construction here and there. Finally the man had reached his destination.

He entered Elis Cafe, and being as it was still quite early, the place was empty. Elizabeth caught his gaze, and he caught hers.

‘Good morning Liz, how are you today’,
Perhaps this was the best part of his day.


‘I’m doing good today, another great day, what can I say. Will you be having the usual’ She said with a smile,
‘Ya, the usual.’
‘Coming right up.’

It was a long and fairly narrow space, the coffee counter was closest to the door, and the pungent aroma of freshly ground coffee pierced the air. The man took a deep breath. He sat close to the entrance and faced the window.

He took quick glances at Elizabeth as she made his cappuccino. She was short with red hair, tied back in a ponytail. She was thin, with a fair complexion and round face, freckles all around. Her cheeks were full, and were died in a lively pink color, she had small lips, and a fair nose. She had deep green colored emeralds for eyes, twinkling and full of life. To him, she was beautiful. He thought of her as wild, untamable, fiery and so full of life.

The man heard the milk steamer stop, signaling that his drink was ready. For some reason he remembered the sweat on his hands that morning. Elizabeth glanced over and with a friendly looking face,

‘Your cappuccino is ready’,

The man walked over, grabbed the cup

‘Thank you’,
‘Have a great day now, I’ll see you next week’

That was the end of his conversation. He never stood long at the coffee shop, he preferred to drink on the go. He had more than enough time to sit down and enjoy his coffee, and sometimes he wondered why he didn’t.

The man marched on, towards where the lumbering giants stood tall. They looked overbearing in the cool and foggy morning. Standing there as if they were the overseers of the city, continuously keeping watch over all its inhabitants. He continued on toward the subway.

Chapter 2

The man was never the first one to work, but he was never the last either. He arrived at his desk and readied himself mentally for another day. He couldn’t say why, but it was Friday and he was happy. He sat down in his chair. It was a rather expensive one that was supposed to help with posture. The company had decided to buy these chairs a couple months back along with stand up desks. When he had sat down for too long he could stretch his legs out a little then sit back down. It was great, he thought to himself.

The man went to the company kitchen for breakfast. If there was a perk he liked it was the free food. Eggs, strawberries, sausage, apples, biscuits, blackberries… The man always had eggs, a couple pieces of bacon, and some apple slices.

He sat down and slowly ate, it was good for his digestion to thoroughly chew his food, he thought. The man remembered the dream that had startled him awake that morning. He had dreamt that he was a wild dog, a wolf. It was hyper realistic, he had been a wolf himself within the dream. He remembered the beginning.

‘’’
The winds were stabbing at his body like tiny icicles, it was relentless but his coat protected him from everything but the sharpest of gusts. The many winters he had lived through had hardened him, he felt comfortable as the cold and sharp winds whipped as his body. He trotted about, and could feel the cold in his paws, the snow had packed during night time and it was almost a foot high. Pines, and brush surrounded him, they created shadows of different sizes, colors and shapes on the ground. He came in full view of the sun as he came to a stop near the edge of the clearing. He closed his eyes and felt the energy of the rays permeate his coat, down to his inner being. He let this kind and gentle wave of warmth overtake him.

He stood looking toward the center of the clearing, three of his pack members were feeding on a young deer, killed just the day before. The dead animal was on its side, ribs sticking outward, with only a few pieces of flesh left. The three wolves fought between what little meat was left on the ribs.

They were all hungry and desperate, but for that very reason they felt much more alive, alert and ready. Soon a boon would come. The great elk migrations were only a couple moons away or so his instincts told him. “They would only need to wait until t…”

The moment of peace came to a crashing halt. The air seemed to split in two as a deafening crack reverberated throughout the misty air.
‘’’

The man worked in one of the new style offices, they called them open space offices. He wasn’t sure about their purpose but the company was very excited about them. They were a big part of the culture as they’re supposed to foster interaction between team members.

His team was working on a new project. It was an extremely important one. The new system they were building would completely revamp the payment system for customers. The new system would make the payment process faster, quicker, and more transparent, both easier for the company and for the customer.

The thing he was most excited for was the new reward system that was being incorporated into payments. It was a system that perhaps hundreds of other companies had already built, but not his company. The company had recently noticed the reward system trend and decided it was best to build one out. One of the benefits was customer retention. The customers would keep coming back for more, because the more they bought the more they could earn in rewards. The man was very excited to be part of something new.

He worked throughout the morning until lunch time. He usually got food with Ryan, his team mate. The man almost never had the opportunity to talk to Ryan casually during work, but it was finally lunch time. They walked together to the company cafeteria, got food and sat down.

Ryan was a bright and cheerful guy, he was also extremely adept at his job. Ryan had a masters degree from Stanford, and everyone on the team had given him a subtle sense of respect, both for his qualifications, but also because of his easy going and cheerful personality. He was well liked by everyone.

Whenever the man had ideas or questions about work he would always talk to Ryan about them. He felt that Ryan could always give him a good opinion.

Ryan started to talk about the weekend. He was going to a club on Saturday, one of his favorite dj’s was playing. On Sunday he would be going to an Italian culture festival. It would be 10 blocks of food, drink, rides and fun. Ryan asked the man if he wanted to go.

The man thought for a moment. On Sundays he usually spent part of his day at Central Park. He liked to walk and get away from the city once in while. He would pretend that he was in the woods in some far off place. It never lasted long but he always felt renewed somehow. The man would not give this up for anything or anyone.

‘Not this time Ryan.’

‘Its ok, maybe next time.’

The man thought he saw sadness and exhaustion in Ryan’s complexion if only for a second before his cheerful attitude took over again. They talked some more before heading back to work.

Chapter 3

It was near the end of the day. Friday was great. The man could leave just a bit earlier and he never felt bad about it. His whole team would do the same.

The man packed his things. He didn’t have much, his work laptop, a notebook, and some pens. He said goodbye to everyone and bid them all a good weekend. He walked to the elevator. He would need to go down 24 floors to get to the bottom.

The elevator stopped on floor 16, 3 people came in.
The elevator stopped on floor 7, 5 people came in.

They reached the bottom floor, and they all moved out one by one. The man thought they seemed similar to ants. They were all part of the same colony, and they both moved in single file. He also felt his coworkers and himself were part of something bigger, together they contributed to the success and the health of the company. The man was glad he had a place where he belonged.

The man had been the first one in and was near the back, he was the last to get out.

As the man walked he thought about the rest of his day, he had made no plans for tonight. He usually read, played video games, and once in a while he would go to the pub to have a drink or two. “First things first”, the man thought, “I need to get home before I do anything”. He took the same route that he had taken on his way to work. He passed Elis cafe and took a glance inside. It was empty now but he remembered his time there that morning.

The man arrived home. He took off a shoe and threw it into the corner, he did the same with his other shoe. The man then placed his satchel near the bed, and threw himself onto the mattress.

The man felt himself sink, like a sinking ship being submerged into the ocean, becoming one with the surrounding water. The mans worries, joys, fears, and responsibilities all melted away as the man lost himself to sleep. It lasted only half an hour. The man sat up on his bed, and grabbed the book on his night stand. Again he lost himself for 2 hours.

It was Friday night now. The man was comfortable, he was relaxing in his apartment. After much back and forth about plans for that tonight, he decided to go to the pub. It was nearby, and it was his favorite pub. The man put the book on the stand, he got up and put his shoes on. He had slept with what he had put on for work, “its still clean, why change”, he thought as he went out the door.

Chapter 4

The man took a sip of his beer. It was quiet, and not many people were there. It was a small bar. There were two pool tables behind him and the orange sheen of the incandescent light bulbs flooded the area. The place seemed a little dirty and grungy, but the man liked it, “its nice if its like this” the man thought to himself. It was ran by an old lady, Mary was her name.

The mans thoughts started to wander, he thought about his week at work, then he remembered his conversation with Ryan that morning. He remembered the glint of sadness and exhaustion that had completely overtaken Ryan. He had seen it before and it always troubled him. It didn’t make sense, Ryan was great in so many aspects, and he had it all it seemed. Ryan had graduated from one of the best colleges in the United States, he was loved by everyone, he was extremely knowledgeable in his trade, and he held a high position within his organization, yet why did he have bouts of melancholy and struggle within himself? What did Ryan have, was he sick, maybe he was just tired, was he bored with his position? The man kept wondering about these questions for a while longer until a man seated himself next to him.

He was tall and handsome. The man had dark hair, short and slicked back. He was a man blessed with good looks, his features were sharp and refined. He wore a white long sleeve button up with slacks and dress shoes, it seemed that he had removed his tie for comfort before hand, yet he was still tucked in. The man thought to himself that this newcomer, seemingly from the upper echelons of society, was out of place in the bar, but was he in a position to make such a claim? The man himself worked for a high tier company. He himself didn’t need to dress so sharply, but he certainly earned enough to be considered upper society. Was he though, did money itself make him upper society? Did money itself make him a better human being? Absolutely not, the notion itself was ridiculous, or was it? The ideal world and the real world were not one and the same.

The man let these thoughts go. He didn’t mind the newcomer, he was going to relax and enjoy his beer. Unexpectedly the newcomer started to talk to him, but deep in the back of his mind the man expected it, almost anticipating the moment that this snazzy man would start talking to him.

“How’s it going buddy.”

“Its going good, pal.”

The man didn’t like the newcomers tone, so he had responded in kind. This sort of situation had never occurred to him, everyone usually kept to their own here.

“Nice shoes you got there, flashy color”,

“Ya, reds my favorite color”,

“No shit, reds my favorite color as well! My names Dmitri by the way. Yours?“

“I’m Adrian, good to meet you”, the man responded.

This was a battle, Adrian thought immediately. Dmitri’s tone of voice, words, poise and body language all led to the same conclusion. A battle to see who could win the other over. Adrian sensed no malevolence, or bad intentions, but he neither sensed benevolence or good intentions. This was a game for Dmitri, and Adrian instinctively knew this.

Adrian was curious about the man. He felt drawn to him, more so they were both drawn to each other. Both knew the game they were playing, and both were willing to play.

Mary interjected.
“Hey honey, are you having the usual.” She asked Dmitri.
“Ya, thank you Mary.”

Adrians phone started to vibrate. He took a quick glance. His boss had sent him a text telling him to take over weekend job duties that Sunday.

“Ahh”, Adrian thought to himself. Memories of his dream that morning started to flood him.

‘’’
It wasn’t thunder, it was gunfire. He recoiled for a second, then quickly scanned the area. Lying next to the deer carcass was one the younger members of the pack. His chest was heaving and struggling to expand out, the pure white snow below him was already being stained bright red.

Through the brush and the pine trees he had spotted moving bodies in the distance. They were about 150m out, with 2 upright creatures, as well as 5 domesticated wolves alongside with them. These domestic wolves were helping the upright creatures hunt their own kind. “Were they traitors?” He thought. “No. They were born and given a place. I was also born and given a place on this earth.” It wasn’t his place to judge who was in the right and who in the wrong, his only responsibility and care in the world were to protect and ensure the survival of his pack. To protect his young who would make up the next generation and to protect those who would teach them. That was his place and responsibility.

He had analyzed his surroundings and had thought these thoughts within a fraction of a second. His mind was running at a pace unknown to him previously before. His muscles started to twitch and spasm as the adrenaline flooded into his system. His movements no longer needed thought, his muscles contracted and expanded naturally, by instinct and experience. He felt an immense increase of pressure in his chest. At this moment life was no longer a passive exercise, it required of him his absolute and undivided attention, his body and actions, his immediate decisions, it demanded of him his whole being.

The air beside him cracked and bent as a gunshot went past him. He took another glance at the party that was pursuing them, their goal was to kill. The hunting dogs were let loose. This would be his final act.

There are 11 pack members, now 10. 3 cubs, 2 older members, 1 youngster, and 4 able hunters including himself. His pack needed to move now to avoid gunfire.

“Could they outrun the hunting dogs while carrying the cubs? No.”

They couldn’t sit still and defend the area either, they would be picked off by the hunters one by one.

“What if they all ran in the same direction and fought only when the hunting dogs came close? No, 3 of us need to carry cubs which would slow us down, that leaves 4 to fight against their 5, but what if their 5th decided to attack the ones carrying the cubs, this would allow the 2 legged hunters to close in on all of us.”

“3 of us will stay and delay the hunting dogs. This would allow the rest of the pack to move toward safety. All 5 of the hunting dogs would attack us as well, they wouldn’t chase the others. 5 against 3 are odds to tempting to let go.”

He looked at the members of his pack. He didn’t need to give out orders. With a look they knew his intentions and his command. The older members and the youngster each grabbed a cub by the scruff, they started to run off in the distance along with his best hunter.

He ran over to the fallen member. His chest slowly heaving, with misty and glossed over eyes. He was at the boundary of this realm and the next. He tapped the fallen members nose with his nose, a solemn and quick goodbye was all he could give. As if waiting for that moment the fallen member closed his eyes, and the heaving stopped. Peace. The deer from yesterday and his friend today, they were different creatures altogether when alive, but here next to each other and in death they were all too similar. No, he thought, they are the same.

As bullet after bullet passed by, he and his 2 hunters moved intentionally and slowly toward a nearby mound, baiting the dogs to that location. The 2 legged hunters would have no clear shot, no line of site. “This will give them 3. No, 2 minutes at most to fight and kill off as many of the dogs as they could”. He snarled and growled, his muscles twisted and wound up ready to explode, anticipating the next second. The dogs were now 20m away.
‘’’

Adrian awoke with a start.

Top Down 2D Character Controller – Unity Tutorial

Created a tutorial for a top down view game, in it we learn how to create and and animate a character as well as create the code to move him around the screen.

Some things to note. In it I use the Rigidbody2D and set its velocity in the Update method. Most times, any code involving the Rigidbody and physics will be put in FixedUpdate as is the standard. In this case its simply setting the speed between 2 values so I deemed it ok.

The Princess Paint Trials GameJam Submission

Heres my game jam submission for the week 88 Weekly Game Jam. It was an interesting little project, and I definitely tried to make the game alive with sound, and different game effects.

I learned that sound in a game is extremely important, especially for the experience that you’re trying to convey. Ask yourself what experiences do you want your players to have? Do you want the player to feel fear, anxiety, happiness, anger or joy? How can sound and music help in this effect? Even though sound is an important part of a game, its still only a small part of the whole experience that a game delivers. You also have the appearance and the type of art that the game uses, the color palette, the game mechanics of the game, the interaction between your character and the world, and many more items. How do you want your game to be experienced by players?

Unity Event Based Health GUI

Learn how to use events to keep track of player statistics, the one I go over in this video is health, but you can change and tweek it for whatever events, data, and gui that you need.

Extra Delegates Info
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/

Extra Events Info
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/


Code
https://github.com/luhdriloh/events_based_ui