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

94 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);
      }
      }

      • using UnityEngine;
        using System.Collections;

        public class CollisionPrint : MonoBehaviour {
        void OnCollisionEnter(Collision x){
        Debug.Log(this.gameObject.name+” hits “+x.gameObject.name);
        }
        }

        Even, generalized not only to spheres but whatever gameobject you put the script to, right?

    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.

              • There is quite a bit of debate about which is better, but there is absolutely no debate about which one runs faster. C# is quite a bit faster than javascript and as a developer faster is always better.

    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.

  • Fantastic tutorials thank you so much..

    Actually i´m using OnTriggerEnter for enemies, but now what i have seen your tutorial, i guess OnCollisionEnter fits better and perfectly…

    Thanks!

  • ahh… i could not make it work with player, it has rigidbody, does the OnCollisionEnter is only for colliders objects?…

    what i want to do is to, when the player touches an enemy something happens (let´s say console says “you hit an enemy”.

    but player does not has collider, it only has rigidbody or character controller, is there a way to make what you have teaching but with player?

    Thanks

  • I know what is happening now, when player hits the cube, nothing happen, but if cube hits the player, then works… , that mean i must to use trigger in enemies ? :( no please!.

    “excuse me cuz too many post..”

  • 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?

    This might be too advanced for this lesson, but I was curious if there was a way to get the name of the object doing the striking as well? Like the others at the top of this thread, I immediately thought to get the name of the object striking the floor for future scripts. However, I noticed when attempting to use gameObject outside of the variable, I am forced to use an instance of UnityEngine.GameObjects… which unfortunately is not yielding the desired results. This is what I have:

    function OnCollisionEnter (theCollision : Collision) {
    Debug.Log(ObjectNames + ” collided with ” + theCollision.gameObject.name);
    /*
    if(theCollision.gameObject.name == “Floor”)
    {
    Debug.Log(gameObject.name + ” colllided with the Floor”);
    }
    else if(theCollision.gameObject.name == “Wall”)
    {
    Debug.Log(“Wall collision”);
    }
    */
    }

    Any thoughts?

  • 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?

    Hello everyone.
    I’m newbie to Unity and your site is very good learning resource for beginners like me. Good job. Well done!!!

  • I wrote my code as followed with same result:


    function OnCollisionEnter(collisiondet : Collision){

    if(collisiondet.gameObject.name == "Floor"){

    Debug.Log("This hit the floor!");

    }

    if(collisiondet.gameObject.name == "Wall"){

    Debug.Log("This hit the wall!");

    }

    }

    Is there a benefit to using the else statement in this scenario?

  • 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.

    • I’m also having this issue. Just started these videos and got to here and this is the first error I have:

      function onCollisionEnter()
      {
      Debug.Log(“!!!!!”);
      }

      Everything plays, but I get no Console message.

      • I’m retarded. I didn’t capitalise the “o” in “OnCollis…”

    Hi, I try your code and its looks fine but it dont work for me. I think I am missing something like adding a rigidbody? or tic or untic some option?

  • Hello all,

    I too have been trying this and am having so many issues. Instead of trying to explain everything can someone look where I posted it on the answers page.

    http://answers.unity3d.com/questions/313767/end-game-script.html

    Much Thanks.

  • You can avoid the if statements with:

    Debug.Log(theCollision.gameObject.name);

    Of course, you won’t get as friendly an output, but it will tell you that it was hitting.

  • Hi these tutorials are helping me a bit because I am really struggling a bit with unity and stuff so its actually helping me a bit to slowly go through these tutorials bit by bit. Also I have came across an issue with this tutorial. here is my problem
    I am using the latest version of unity and this happened
    I did your code like it is in the comment box under your vid

    function OnCollisionEnter(theCollision : Collision){
    if(theCollision.gameObject.name == “Floor”){
    Debug.Log(“Hit the floor”);
    }else if(theCollision.gameObject.name == “Wall”){
    Debug.Log(“Hit the wall”);
    }
    }

    and for some reason it keeps coming up with this red error message
    Script error: OnCollisionEnter
    This message parameter has to be of type: Collision
    The message will be ignored

    that’s the message I get when I try this script so have you got any ideas and any help would be appreciated. Btw I am also on the bolton uni games design course as well :).

  • The provided script gives error with unity 3.5.6f4 :

    Script error: OnCollisionEnter
    This message parameter has to be of type: Collision
    The message will be ignored.

    The following script worked for me :

    //Basic collision detection checking for two differently named objects
    function OnCollisionEnter(theCollision : UnityEngine.Collision){
    if(theCollision.gameObject.name == “Floor”){
    Debug.Log(“Hit the floor”);
    }else if(theCollision.gameObject.name == “Wall”){
    Debug.Log(“Hit the wall”);
    }
    }

  • I am a student of c-sharp script how can I covert these java scripts to c sharp, I am totally new to programming .

  • C# code:

    [code]
    using UnityEngine;
    using System.Collections;

    public class BoxDrop : MonoBehaviour {

    // Basic collision detection checking for two differently named objects
    void OnCollisionEnter(Collision theCollision)
    {
    if(theCollision.gameObject.name == "Floor")
    {
    Debug.Log("Hit the floor");
    }
    else if(theCollision.gameObject.name == "Wall")
    {
    Debug.Log("Hit the wall");
    }// End if
    }// End OnCollisionEnter method
    }// End BoxDrop class

    [/code]

  • I have had a problem with a collision detection that is meant to cause a few events to take place, but the collision itself is not being registered so the events are not being triggered.

    this is the first code for the first collision (of 2):

    var Collectible2 : GameObject;
    var GUI1 : GUIText;

    function OnCollisionEnter( collision : Collision )
    {
    if ( collision.gameObject.Name == “Graphics” )
    {
    Debug.Log( “Collision: Detected (Graphics)” );
    Destroy( gameObject.Find(“Collectable1″) );
    transform.GUI1.Text( “Well Done!” );
    yield WaitForSeconds(5);
    Collectible2.MeshRenderer.Enabled = true;
    Collectible2.Collectible2Script.Enabled = true;
    Collectible2.ParticleRenderer.Enabled = true;
    transform.GUI1.Text( “Now Find The Second Collectible >:D” );
    yield WaitForSeconds(5);
    transform.GUI1.Text( “” );
    }
    }

    and this is the second (Not sure if this one isn’t working as that code is meant to set it off):

    var EndGame : String;

    function OnCollisionEnter(EndGameCollision : Collision)
    {
    if(EndGameCollision.gameObject.name == “Graphics”)
    {
    Application.LoadLevel(EndGame);
    Debug.Log(“Collision: Detected (Graphics)”);
    }
    }

    I also originally had all of the script on one document:

    var readynow : boolean = true;
    var seconds : float = 5;
    var gui : GUIText;
    var nextlevel : String;
    var collectible1 : GameObject;
    var collectible2 : GameObject;
    var Spawnpoint : GameObject;

    function OnCollisionEnter(Collectible : Collision)
    {
    if(Collectible.gameObject.name == “floor2″)
    {
    Debug.Log(“Collision: Detected”);
    }
    if(Collectible.gameObject.name == collectible1)
    {
    Debug.Log(“Collision: Detected”);
    destroy();
    create();
    GUIdisplay();
    if(Collectible.gameObject.name == collectible2)
    {
    Debug.Log(“Collision: Detected”);
    destroy2();
    }
    }
    }

    function destroy()
    {
    readynow=false;
    Destroy(gameObject.Find.collectible1);
    yield WaitForSeconds(seconds);
    Destroy(gameObject.Find.Spawnpoint);
    }
    function create()
    {
    readynow=false;
    Instantiate(gameObject.Find.collectible2, Spawnpoint.position, Spawnpoint.rotation);

    }
    function GUIdisplay()
    {
    transform.gui.Text(“Well Done! Now Find The Second Collectable”);
    }
    function destroy2()
    {
    readynow=false;
    Destroy(gameObject.Find.collectible2);
    Application.LoadLevel(nextlevel);
    }

    but I don’t need that one analysing, just the other two (albeit more efficient, I am a beginner so I should probably just stay with the other two)

    thanks,
    Tim

  • Great tutorials , there relevant/working with the new unity 4.x as well.

  • Woohoo!

    I’ve been a unix systems programmer all my life, what a breath of fresh air Unity is!

    Thank you for these tutorials, almost had an orgasmic moment connecting code and visuals, can’t wait to go crazy with this stuff :D

    Cheers!

  • Hello, I know this is pretty old article, but maybe someone will answer me, I`m using Unity, its not the newest one but one of the newer ones (cant remember the version) (Windows) and I have done everything till it should print the text, but it doesn`t, code is exactly the same as in the video, everything looks the same, except it doesnt print anything,
    I have checked console and its clear.
    I have checked if I applied my script to the right one – and yes I did.
    I have saved the script and the color on the side have changed from yellow to green.
    Yeah thas pretty much it, please help :)

  • Hi,

    How to define particle 2 tag. one is coalition(particle coal lid but not destroy ) tag or second tag is(if particle coal lid with this tag then ) individual particle destroy.

    ple….help me

    play_edu

  • So, quick question on scripting. Why all of the tabs, and Parentheses? Same with {‘s (not sure of the name) Is it just preference for easy reading, or do they serve a purpose?

  • Hi! I have a question. How do you learn scripting in Unity 3D? I can’t really find any tutorials but do you or anyone on here know about books or tutorials for scripting? Thanks! =)

  • Hi there,
    I know this is a pretty old thread but I am hoping someone can help me anyway as I am new to Unity and I am running Unity 4 I believe. I am having trouble with the code in this tutorial. Here is the code I have:

    boxdrop.js

    function onCollisionEnter(){

    Debug.Log(“Hit Something”);

    }

    This code doesn’t produce any compile errors but it also doesn’t print any messages to the console.

    I took a programming class in University so I know the importance of having the code exact but this is the second time I have been following a tutorial in Unity and have the code exactly copied but it still doesn’t produce the results I am looking for.

    I guess the only thing I have done differently on my project than the one in the video is that I have a folder in the “Project” area of Unity that houses all my scripts. I should also mention that while I was doing the “B00″ tutorial I needed to create a script called “bounce” because even though I imported Standard Assets I wasn’t able to select the Bouncy trait like he did in the previous video. Someone please respond!

    • Never mind. the error was on the function name should be “OnCollisionEnter(){}”

    Hello, I would like my game to move two balls to random locations when they collide. I used Random.Range() to pick a random number for the transform.Translate function but I can’t seem to find the correct range for my world. My world is 200p wide, 600p tall, and 200p long. PLEASE HELP!

  • Hi,

    great Tutorial everything works for me except the Console only displays the first hit.
    Fot this tutorial its not a big issue, but since im a Beginner i am afraid i may have made some mistake wich will hurt me later on.

    My Code seems to be the same you use so maybe it has something to do with my unity settings?

    function OnCollisionEnter(theCollision : Collision){

    if(theCollision.gameObject.name == “Platform”){
    Debug.Log(“Hit the floor!”);
    }else if(theCollision.gameObject.name == “Wall”){
    Debug.Log(“Hit the Wall!”);
    }

    }

    • *edit*
      ofcourse i named my floor “Platform” but also when i change the name and code to “Floor” i only get one respons although it hits several times.

      • allright i found my mistake:
        got “Collapse” activated in my console once i turned it off it works fine.

        sorry for flooting here

    I have almost no knowledge of coding but I can somewhat understand this. I have been trying to learn to code for 3 months but haven’t beenable too and this is the only place I know of to get started. Thanks for the video

Leave a Comment