Jump to content
  • entries
  • comments
  • views

100 Days of VR: Day 20 Fixing Game Object Collider in Unity

Josh Chang


Welcome back to another exciting day of Unity development at day 20! Can you believe it? We’re 1/5 of the way to 100 days! I’m hoping that the momentum will keep me going forward until I ship something!

Now looking back at day 19, we created a health system that we can now use, however we encountered a problem.

For some reason, our collider only hits the enemies once even if we go through the attack animation multiple times.

Today we’ll be solving that problem. So, let’s get to it!

Fixing Our Mesh Collider

The problem lays with the Mesh Collider that we created for our knight on Day 12. Remember this?


That standing mesh collider, is literally what we’re colliding with every time the Knight attacks us.

The problem is that Mesh Colliders can’t follow animations of the model, as a result when the knight first touches us, the mesh might touch us, but afterwards it we, the player, don’t get pushed back by the collider, the mesh will never touch us again.

Here’s a picture to demonstrate the problem:


While the knight model itself might be touching us, our Mesh Collider is static and doesn’t move.

This isn’t good! We want to damage our player when the knight’s fist contacts the player! Not this static mesh collider!

Some changes are going to be needed to fix this problem.

  1. We still need our Mesh collider. This prevents us from walking through our enemy. Right now, we have a problem where we can walk over the knight, but we’ll fix this now.
  2. We’re going to add a Box Collider to the hands of our Knight. This way, we’ll know for sure when our player gets punched.

Fixing the Mesh Collider for the Knight

Right now, we can’t move our mesh, because it’s in the parent body. According to this post about incorrect mesh positioning, we will make a new empty object and add the mesh collider there.

This works for us, because we only need the mesh for collision detection and for our raycasting for shooting.

Let’s do it!

Originally, we put the Mesh Collider in our knightprefab game object. Let’s remove that now.

Select knightprefab, right click, and select Create Empty, to make a new Game Object. Let’s rename this object to Collider.

Select Collider and add a new Mesh Collider component to it. For the Mesh, select body to get our Knight model back.

You might have to move Collider around yourself to get the collider to match our knight, however, at the end you should have something like this:


Now with this, we can’t just walk over the knight.

Adding new Colliders for our Fists!

Now that we have solved the Mesh Collider problem, we’re going to fix our original problem with dealing damage when the enemy attacks us.

To do this, we’re going to add box colliders, just to the fists of our knights. Specifically, in knightprefab -> hips -> spine -> chest -> L_shoulder/R_shoulder -> all the way down to L_Wrist/R_Wrist.

For each box collider, I made the scale of the box to be 0.25 to fit the size of the hand.


Now that we have this, we need to attach a script to each of our hand models that can detect the collision. Scripts from parent objects can’t detect collision for it’s children.

It’s also important that our original script: EnemyAttack, stays where it is, because we need access to the animator component that’s located in the parent.

To solve our problem, we’re going to move the collision part of our code from EnemyAttack to a new script called FistCollider.

FistCollider will deal with the collision of the knight fists and we’ll get the results in our EnemyAttack script.

Here’s our FistCollider script:

using UnityEngine;
public class FistCollider : MonoBehaviour
    private GameObject _player;
    private bool _collidedWithPlayer;
    void Start()
        _player = GameObject.FindGameObjectWithTag("Player");
        _collidedWithPlayer = false;
    void OnCollisionEnter(Collision other)
        if (other.gameObject == _player)
            _collidedWithPlayer = true;
        print("enter collided with _player");
    void OnCollisionExit(Collision other)
        if (other.gameObject == _player)
            _collidedWithPlayer = false;
        print("exit collided with _player");
    public bool IsCollidingWithPlayer()
        return _collidedWithPlayer;

Here’s the flow of the code:

  1. Like our EnemyAttack script, we want access to our player game object and we want to check if we collided with the enemy.
  2. In Start() we make sure to instantiate both of our variables.
  3. In OnCollisionEnter() and OnCollisionExit(), if whatever we collided with is the player than we would set our boolean flag. Once again this is exactly the same as
  4. In IsCollidingWithPlayer() we would give our bool _collidedWithPlayerto whoever calls it. Note that this function is public so other script can have access to this. We’re going to use it later.

Let’s attach the script to both L_Wrist and R_Wrist.

Now that we moved part of our collision code from EnemyAttack to FistCollider, let’s use FistCollider in EnemyAttack. Here’s the code:

using UnityEngine;

public class EnemyAttack : MonoBehaviour
    public FistCollider LeftFist;
    public FistCollider RightFist;
    private Animator _animator;
    private GameObject _player;
    void Awake()
        _player = GameObject.FindGameObjectWithTag("Player");
        _animator = GetComponent<Animator>();
    void OnTriggerEnter(Collider other)
        if (other.gameObject == _player)
            _animator.SetBool("IsNearPlayer", true);
        print("enter trigger with _player");
    void OnTriggerExit(Collider other)
        if (other.gameObject == _player)
            _animator.SetBool("IsNearPlayer", false);
        print("exit trigger with _player");
    private void Attack()
        if (LeftFist.IsCollidingWithPlayer() || RightFist.IsCollidingWithPlayer())

Here’s the changes in our code:

  1. First, we create new public variables: LeftArm and RightArm that are the FistCollider script that we just created.
  2. We cleaned up a lot of the code, specifically the Collision part and anything that had to do with it.
  3. In Attack() we use our new FistCollider to make collisions with the player and then when the attack event from our animation gets fired, we check if the player gets hit. If they do (meaning the knights fist collided with the player), the player will take damage.

With our script done, the final thing that we need to do is to make sure that we attach the FirstCollider object to our player.

We can directly attach our game object into the spot and the script will be automatically selected.

When you’re done, we should have something like this:



Phew that was a lot of work!

In these past 2 days, we created the health system and we re-visited some of the existing problems with the enemy knight’s mesh collider such as walking over them and not accurately colliding with the player.

We also separated out the code with attack collision work while still making our original collision script work as normal.

Now that we finally have health for our player, tomorrow, the next thing we’ll do is start working on an end game state for when the player’s health reaches 0.

Until then, have a nice evening, I’m going to sleep!

Source: Day 20

Visit the 100 Days of Unity VR Development main page.

Visit our Homepage


Recommended Comments

There are no comments to display.

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 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.
    • By GameTop
      Dirt Bike Extreme - another game made with Unity. Took about 2 months to complete.
      Take part in extreme motorcycle races across the dangerous and challenging tracks. Dirt Bike Extreme is easy to pick up but hard to master. Race, jump and crash your way and other mad rivals through the amazing tracks as you master the skills and physics of motocross in this high-speed racing adventure. Conquer challenging routes on 23 different runs, discover new bikes and become the best of the best! Over 257K downloads already!
      Windows Version:

      Mac Version:


    • By Sergio Ronchetti
      Continuing to work on “Eldest Souls” (first article here!), I’ve begun familiarising myself with the workflow between Fmod and Unity, and the integration system. I know much of this will be pretty obvious to most, but I thought I’d share my thoughts as a complete beginner learning the ropes of sound designing. 
      The library of sounds that Fmod provides has been very useful, at least as reference points. I’ve still kept to my ethos of producing the sounds myself as much as possible. Having said that, Fmod gives you 50 free sounds with your download, and I’ve used a wooden crate smash, a drawbridge and electricity sound you can hear in the foley video below.
      The thing i found most useful was witnessing changes i made in Fmod being realised instantly in Unity. If a volume needed changing, or the timing of one of my effects was off, i can literally switch to Fmod and then back to Unity and immediately see the result of my alterations. It also seems apparent that using middleware such as this (or i've heard Wwise is also equally intuitive) grants the developer, and myself included, a great deal more flexibility and opportunity to edit sounds without going all the way back to a DAW, and bouncing down again. Needless to say, my workflow is so much faster because of it.
      I've also loved the randomised feature of Fmod, whereby any sound can be made to sound slightly different each time it is heard. Taking a footstep recording i made for example, I was able to add further authenticity of uneven footsteps by randomising the pitch and volume of each playback. 

      I used this technique when creating footsteps for the first major boss in the game called "The Guardian". A big, over-encumbered husk of a monster. I also had fun rummaging through the garage for old tools and metal components for the “Guardian” (the first boss) footsteps. See below!
      I also created a sword attack for our player, trying to sound different from the generic “woosh” I see in so many video games. I used a very “sharp” and abrasive sound to differentiate him from any enemies.
      On another note, I recently upgraded my microphone to a Rode NTG2 shotgun, which has been phenomenal. I haven’t had to worry about noise interfering with the clarity of my objects, whereas before with the sm58 I had to be clever with my EQ and noise reduction plugins.
      Important to note again that this still a “cheap” mic in comparison to most other products on the market, and all in all my entire setup is still very simple and affordable which I’m quite proud of. I’ve seen many musicians spend heaps of money on gear they don’t necessarily need. I much prefer being resourceful with less equipment, than to have more than I can understand or remember how to use.
      It’s forced me to understand every aspect and capability of my tools, which I believe is a principal that can be applied to any discipline.
      I have more fun little sound effect videos on my Instagram for those interested, where I post regular updates. Thanks for reading! (if you’ve made it this far)
    • By Sergio Ronchetti
      Recently I joined the talented team at Fallen Flag Studio as the composer for their latest release "Eldest Souls" which consequently lead me into a field I have always dreamt of trying - sound design!
      Having no prior experience, I began watching a few online tutorials (if you want to learn from anyone make it Akash Thakkar from "Hyper Light Drifter"... what a guy!) and basically just testing stuff out i found around the house. Luckily my dad has a garage FULL of random crap to use.
      Before i continue, it's important to note that i DO NOT have fancy equipment, meaning anyone can try this. (my equipment is an sm58, focusrite scarlett interface and Logic Pro X plugins... that's it!)
      I started basic with some footsteps, which weren't all too difficult. Then I moved on to projectiles and a spear attack one of the bosses has. Below are a couple super short videos on my resulting attempts.
      Amazing how great a banjo sounds for that typical "woosh" sound! And if you're wondering, the paper was added to give some texture to the jab.
      I could be finding a lot of these sounds in libraries online (like the built-in ones that come with Fmod and Unity) but I've chosen not to, in order to produce authenticity and hopefully a more unique gameplay experience for players when the final product is put together.
      P.S. if you'd like to try the game and hear my hard work we'll be at EGX and several other conventions later this year, soon to be announced! Thanks for reading!
      To those interested, there's an Alpha trailer of the game in question below.

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!