Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Collision scripting.

Discussion in 'Scripting' started by Dinglevak, Apr 27, 2014.

  1. Dinglevak

    Dinglevak

    Joined:
    Apr 23, 2014
    Posts:
    3
    Hi, I want to make a Java script code for when my 1st person character collides with a cube it destroys it. None of the coding/scripting or tutorials I have found have actually worked, and some have actually caused more problems! when someone writes gameobject in an example script are they expecting me to replace it with 'cube'?.

    Does my 1st person character need to have a mesh collider? does it need to be a trigger?

    Does the cube need to be a trigger, rigid body?

    I really need help with this, as everything I've been told just causes errors!

    Thanks for any help :)
     
  2. Suddan

    Suddan

    Joined:
    Jan 12, 2013
    Posts:
    21
    If someone types 'gameObject' it is always the object the script is attached to, whereas 'GameObject' is a reference type ( a class).
    gameObject is an instance of the type GameObject.

    I did my best to write a simple code in JS for you, i usually never use JS though and hope it works fine for you.
    Dont forget to set the tag of the objects you want to destroy to "Cube" (or any other tag as long as you change it in the script).

    This only works if you also use a CharacterController component on your players gameobject, if you want to do the same with rigidbodys, it's quite similar although the movement should rather be done in FixedUpdate instead of Update.

    Code (csharp):
    1.  
    2. var charController : CharacterController;
    3.  
    4. function Awake()
    5. {
    6.     // get a reference to your characterController component so that you can access its methods and attributs
    7.     charController = gameObject.GetComponent(CharacterController);
    8. }
    9.  
    10. function Update()
    11. {
    12.     // here comes your control-logic for the character, for a simple test we'll just move it 1 unit/second
    13.     charController.Move(Vector3.forward*Time.deltaTime);
    14. }
    15.  
    16. function OnControllerColliderHit(other : ControllerColliderHit)
    17. {
    18.     // only destroys gameobjects that have the tag "Cube"
    19.     // don't forget to set it in the inspector of the object that you want to destroy
    20.     if(other.gameObject.tag == "Cube")
    21.     {
    22.         Destroy(other.gameObject);
    23.     }
    24. }
    25.  
     
    Last edited: Apr 27, 2014