unity 3d student

Beginner B01 – Basic Collision Detection

How to detection basic collisions between objects using scripting.

Code Used

//Basic collision detection checking for two differently named objects
  1. function OnCollisionEnter(theCollision : Collision){
  2.  if(theCollision.gameObject.name == "Floor"){
  3.   Debug.Log("Hit the floor");
  4.  }else if(theCollision.gameObject.name == "Wall"){
  5.   Debug.Log("Hit the wall");
  6.  }
  7. }

Further Reading

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

63 Comments

    Great tutorial!
    Without getting into data objects or other topics that don’t necessarily belong in a beginner’s tutorial may I suggest a bit of code that some might find useful?

    function OnCollisionEnter(theCollision : Collision){
    Debug.Log(“Hit”+ theCollision.gameObject.name);
    }

    This will name any object that your box hits. Not so much an asset with just a floor and a wall but if you use this debugging function on later projects it’ll save quite a few lines of code over an extended If-Then statement.

    Thanks again.

    • Haha Jake, I immediately thought the same thing when watching the video and then subsequently did it when I reproduced in my project.

      I must say that I’m completely new to Unity, I’ve had many times where I tried to learn Unity and failed. These videos have been a tremendous help to getting me situated and more comfortable with the way Unity operates.

      On to the next video!

    • Haha, my mind went to the same place as well..

      I’m in C# so I ended up with:

      using UnityEngine;
      using System.Collections;

      public class ItemCollision : MonoBehaviour {
      void OnCollisionEnter(Collision collision) {
      Debug.Log(“Collided with ” + collision.gameObject.name);
      }
      }

    Hi Jake

    I think Will is trying to demonstrate control flow of simply if my object hits “THIS” do something specific…
    ;)

  • Hi,
    I really like your tutorials. They are easy to understand and not to long. I was just wondering whether i can use the same code here but instead of using javascript use c#, because im already familiar with it.
    Thanks,
    Karthik

    • Hi Karthik, yes you can use the same code in in c# but the syntax is different. I’ll try and make an essentials tutorial for people unsure of this at some point today.

      • Thanks,
        That seems to be a problem with many unity tutorials, they assume you are using javascript. I read the Scripting in C# article on the website, and it seems like you can use the same code, you just have to use c# syntax, which requires extra typing. But im not going to do any hardcore stuff with this so I guess its fine.

        • I, too, am jumping in with C# Karthik. As you mentioned, the website article is pretty brief. If you go the C# route, I HIGHLY recommend using Visual Studio as your editor. The intellisense it offers is an IMMENSE help and definitely eases the lack of Unity tutorials targeted at your scripting language of choice.

          • I would suggest to use C# just for the classes that does something complex; and for the rest of the scripts just use JS, since is quicker

            I made various script to process data, make calculations and do game logic in C# on win; testing it in there with a dummy main()

            Then i call them via a JS script in Unity, passing what they require and managing the return values, and it works like a charm :)

            It takes a bit to get used to switch between both, but then it gets natural, like speaking 2 languages

            • There is a lot of debate around the usage of either language and I agree with you that its an idea to be aware of both – we’re simply sticking with JS on this site to assist users newer to programming as its simply shorter – ignoring the efficiency from the equation, the point here is to help people get started in learning the right way, so hopefully simpler languages can be helpful with that as code is often a stumbling block for many beginners.

    Awesome, but please, can you make 2 modifications?

    1) add a next, previous button, so we can go back and forth the various modules in each category?

    2) the font of the code snippet is small; could you make it a little bigger?

    Thanks!

    • Those two are both big on the to do list – the font size was something that broken , I just need to fix the CSS of the site to bring it back up, it was bigger before, I promise! (that’s not a phrasing I should repeat eh?)

      • Hi, your tutorials are great but i have one question…. I typed in the code but when i press play it plays but in the bottom left corner it says “The reference script on this Behaviour is missing.” What does that mean and what do i do ??? I am a noob to all of this so im watching every video carfully.. I am 13 years old and want to make games and make money off of the games i make :) That would be awesome… THANKS AND GREAT TUTORIALS !!! :)

        • Hi thanks! if you’ve deleted or had an issue with corrupt project then this can happen, but its quite unlikely.. still having this issue?

      hey mate, i was actually going to comment about this but as i read down i saw that others have already expressed their interest in a back and forth button so we dont have to constantly go back and then select the youtube videos. i’d watch them on youtube for this feature but then we lose your great code snippets.

      the tutorials are great, much appreciation!

    Thank you for the tutorials; we have to use these in uni (Computer games design) and I think they are excellent tutorials; very precise and informative; also bought a copy of your book.

    • Hi Rio, what University is your course part of? I’d love to get some feedback from your tutor if possible.

      • The University of Bolton. Computer Games Design.

        If possible may I ask if you have any tutorials on the difference between 2.6.1 and 3.0

        I normally do not like scripting; but the game object class idea is amazingly easy to understand and I think your tutorials are very useful and straight to the point.

        PS thank you for replying.

        • Sorry forgot to ask how do I go about contacting you as i would send you my lectures contact details and name but I do not want to post the details where they (the details) may be seen by anyone else.

    Hey man,
    This tutorial is absolutely great for beginners! Good work!

  • Hi bro, nice tutorial but i’ve got a problem!
    I tried to use your script, but Unity always gives me an error like “Errore Char …”, other times it crashes! I know i’m a noob lol, can you help me ?

    • Of course – post your script to http://www.pasteit4me.com, selecting the language you’re using (presumably javascript) from the drop down on the right and then post the link back in this comment thread. That said, the error reporter is usually correct, can you also post what it’s telling you by copying the error from the unity console window (to open it press ctrl-shift-c or cmd-shift-c on mac).

    OK, here’s the link : http://www.pasteit4me.com/1403001

    • You shouldn’t be getting those errors, are you in the latest version of Unity?

    function OnCollisionEnter(theCollision){
    Debug.Log(“hit” + coll.gameObject.name);
    }

    • presumably you mean ‘Debug.Log(“hit” + theCollision.gameObject.name);

    Hi. Really loving your tutorials.

    However, I’ve been getting an error message with the code you provided.
    It says Script Error OnCollisionEnter.
    After typing in the code myself I was getting an error and then I pasted in your code and the exact same error occurs.

    If I try to do this “function OnCollisionEnter (thecollision)” I get the error message classID >= ms_MaxClassID || classID < 0

    I should also note that I am using the Unity Script Editor, not the one provided with Unity – maybe that application is causing problems.

    • Not sure I follow you, can you paste the exact error, and what your script has in it exactly to pasteit4me.com and reply with links to both or just the script and post the error message in your comment, thanks

    • well try Unitron (mac) or Unisciite (pc) and see what you get, otherwise its not a script error per se so reinstall Unity and make sure, or simply restart it, or reimport the script asset having closed it in your script editor, to do this, right click on it in the Project panel and select reimport.

    Two questions for this:

    First, is there an advantage to using else if for the two collison checks, rather than just closing one if statement and opening a new if statement?

    Second, could you step me through the use of arguments? What purpose is (theCollision:collision) serving? In what general situations should I look to use arguments?

    • No advantage but it should make sense that if you’re expecting one object to hit at present, you’re not expecting to deal with a collision of something else at the same time, hence ‘else if’ rather than two potential ‘ifs’ at once. As for arguments, you use them to draw information from the function you’re working with so in the case of the Collision type argument, this will allow you to refer to the collision that has occured, if you look at the script reference on the Collision class, you’ll see what other information, aside from the particular object it is, you can find out – http://unity3d.com/support/documentation/ScriptReference/Collision.html

      • I think I get it…I’m going to try restating in my own words – it helps me make sure I’m actually understanding the concept. See if this sounds right.

        OnCollisionEnter is a special function that generates a bunch of information in a specific circumstance (a collision).
        By entering an argument, we’re saying “Create a new variable, and out of all the information available, store the ‘Collision’ information generated by OnCollisionEnter.”
        Then we can do whatever we want with that variable.

        Another Unity tutorial I did had me create a new function, Card, with arguments, so it looked like function Card (name:String, id:int);
        When I call that function, I can send some information along with the call. The arguments I entered let the program know that it should save the first bit of information as a string variable called “name”, and the second bit of information as an id variable called “int”.

        So: the reason I would use an argument is if I want to collect and use information that has been passed to a function, whether that information is being created and passed an inherent feature of the function, or has been passed to the function by another part of my script.

        • You’re NEARLY there! Just a couple of things I’d pick you up on here – first off your arguments / variables aren’t called ‘int’ in your example, that is the type of data. The name of the variable was ‘id’ and it was an integer – a whole number. This may look confusing as in function arguments, unlike other variables, you wouldn’t write ‘var’ beforehand.

          The only other thing to note is that you say ‘out of all the information it stores info on collisions’ – whilst true this is the piece of information that function provides so there isn’t other info to glean from a collisionenter – if you see what I mean? Hope this helps! good luck :)

          • Thanks, Will – I think I did mean int variable called id, and just got the sentence backwards. (It’s good to be called on it; I know the code won’t forgive me for the slip!)

            On the collision information, I think I was assuming that I could use, say,
            function OnCollisionEnter (theCollision: gameObject){};
            to get the gameObject collided with. I should be looking at it more broadly – using (theCollision : collision) to store the collision, then later using
            var hitObject = theCollision.gameObject;
            to pull information out of the collision and determine what was hit.

    I’ve got this problem with scripting. I want two objects to disappear when thye touch each other and create a particle system. This is the code which I’ve got.
    var explosion : ParticleEmitter;

    function OnCollisionEnter(theCollision : Collision){
    if(theCollision.gameObject.name == “Character”){

    Instantiate(explosion, transform.position, transform.rotation);
    Destroy(gameObject);

    }
    }

    • OK 2 things – which object is this script attached to?, presumably something which will hit an object called ‘Character’, and what is happening / not happening?

      So far it looks correct but if you want both this object and the ‘Character’ object to disappear you’ll have to add Destroy(theCollision.gameObject); in addition to your existing Destroy(gameObject); as that is simply destroying the one which the script is attached to.

    Hello,

    I’ve imported an asset from a 3ds file.
    Then created a prefab for this file.
    The rigibody component does not work as it should be. Only gravity works, but collision does not.

    What should I do?

    thanks in advance for any help

    • First off, check you haven’t checked ‘is trigger’ – that would mean objects pass through this as it’s collider is made into a trigger area rather than a physical reaction.. if that makes sense. if not look at the docs for triggers. Next step, post a tinypic showing your setup of the object in the inspector..

      • Thanks Will for your reply!!!

        Here is the link http://tinypic.com/r/sbklyc/7 showing the setup of my prefab (container20).
        Just for your information, “is trigger” is not checked and no success, I also tested with this option checked and nothing, the container fall down and do not stop when achieve the plane.

        I really do not know what to do!!!

        I need this working otherwise I will not be able to go on my project…

        thanks for any help

        dani

        • Hi Dani, it’ll be that your plane has a mesh collider and so does your object – two mesh colliders dont work together. Put a primitive box collider on the plane to replace the mesh collider and it should work!

          • Thanks a lot! It works now, great…
            I’m an experient programmer but this is my first app with 3D. Your videos and your attention are being very usefull and important.

            best regards,

            dani

    Hi!
    I have a big problem with this one.
    The objects I want to check collision with are not rigidbodies. I read in the scripting reference that this only works if a rigidbody is attached.
    How would I check collisions for non-rigidbodies?
    (I get no coding errors, it just wont detect anything. Copied your code. Even tried OnTriggerEnter.)

    • Hi PB, no you’re missing a detail – at least one of the objects in the collision must be a rigidbody, that is why the cubes and other primitives in most of these modules are set to fall – they have rigidbodies and this is a simple way to show off collision.

    Oh. Now I understand.
    The problem is still there however, as I want a spawned prefab to check collisions with exactly the same prefab xD.

    Spawning lots of trees at random positions.
    if they collide with a tree – get a new random position.

    Should I maybe add a non-moving rigidbody to the tree and check collision with that instead?
    Long time since I used unity xD

    • Yay, it worked :D!
      Just added a kinematic rigidbody!
      Thank you ^^!

    • No you’ll need a more detailed solution – ideally establish a grid of potential tree positions using an array and a for loop, and then check the array to see if a tree position has already been filled, I did this recently with placing a large group of enemy positions in a game, worked well.

    Hello! Could you please tell me the difference between Collision.rigidbody.position and transform.position? When a gameobject is colliding with another gameobject.

  • Great tutorial, altough I am new and I don’t know neither C nor Javascript.
    I think java is easier to start, would you advise it?

    • Really doesn’t make too much different, it is easy enough to make the leap to C# when you are ready. Note that the script reference lets you toggle between languages.

    Hi, I’ve got a collision detection script that if i put on a pipe that is attached by script to my models hand, and when he hits anything with it, it does not work, is this right?, the pipe and the item being hit have colliders on them, I’ve tried this simple script to test.

    function OnCollisionEnter() {

    Debug.Log(“Hit”);

    }

    is it because the pipe is attached to the hand by script??

    by the way your videos are a great help .. thanks

    • When you say ‘attached by script’ what do you mean? is it a child object?

    I’m having a scripting issue.

    function OnCollisionEnter(theCollision : Collision){
    if(theCollision.gameObject.name == “Bullet(Clone)”){

    Destroy(gameObject);
    }
    }

    I tried having this attached to my box and got nothing. No errors, and they my bullet moves the box when it hits, but the box doesn’t disappear. I also tried the other way around with:

    function OnCollisionEnter(theCollision : Collision){
    if(theCollision.GameObject.name == “Box”){

    Destroy(GameObject.Find(“Box”));
    }
    }

    I attached it to my bullet, got the same thing. Definitely a collision, but the box refuses to disappear. Any help with this issue would be much appreciated.

    • Apply it to whatever you are shooting and say -

      function OnCollisionEnter(theCollision : Collision){
      if(theCollision.gameObject.name == “Box”){
      Destroy(theCollision.gameObject);
      Destroy(gameObject);
      }
      }

    Hi I am trying to set up a collision between a car and and a monster truck where the car deletes and an explosion is set off in unity but the code does not exc if you could help it would be much appreciated.
    Here’s what i got so far

    // – instantiates a explosion prefab when hitting a Monster truck

    // – then destroys car

    var explosionPrefab : Transform;

    function OnTriggerEnter(Car:Collider)

    {

    // Rotate the object so that the y-axis faces along the normal of the surface

    if(Car.gameObject.name == “Car_Model”)

    {

    var contact : ContactPoint = Car.contacts[0];

    var rot : Quaternion = Quaternion.FromToRotation(Vector3.up, contact.normal);

    var pos : Vector3 = contact.point;

    Instantiate(explosionPrefab, pos, rot);

    // Destroy the projectile

    Destroy (gameObject);

    }

    }

    • What IS happening when you do this? could use more info to help you… do u have script errors in the console?

    Great tutorial. I love this site, I was refered to it by another programmer on unity forums, because I am totally new to Unity. Been thru the Essentials vids and now starting on these and looking foward to it. Again great job WG

    • Also on another note, I have been through all the tutorials, and done the challenges, now i am making my own challenge 4, I have a couple problems though. It seems http://www.pasteittome.com is nolonger working, and second its a script problem so its better if your seeing what im trying to explain.

      • pastebin.com instead, but yeah it used to be pasteit4me.com

    Why does unity say ” All compiler errors must be fixed before entering playing mode” ? I copied everything he did…. SOMEONE PLEASE REPLY !!!!

    • You’ve copied it wrong! the console should tell you where the mistake lies in your script. Feel free to put a link to your script on pastebin.com.

    Hello. Does this code still work with the newest version of unity? I am trying it, but for one thing “Debug.Log” doesn’t change colors so I don’t think it recognizes the code or something. I’m not too sure. Any assistance with this?

    • Yes, nothing here has changed.

Leave a Comment