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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Become Child on Trigger Enter, but stop being Child when out of trigger

Discussion in 'Scripting' started by jorn818, Oct 20, 2015.

  1. jorn818

    jorn818

    Joined:
    May 12, 2013
    Posts:
    97
    So I got this system were you can build spaceships with blocks (kinda like Starmade)

    however the character cant walk around the ship he/she just glides off. So I have a chair with a trigger object
    on the chair (a cube) so what I need is the moment the player walks into the trigger the player becomes child of the chair, (the chair is parent of the ship) but the moment the player walks out of the trigger it isnt a child anymore of the chair...

    Anyone know how to do this because I did do triggers in the past but I have no idea how to do this
     
  2. vintar

    vintar

    Joined:
    Sep 18, 2014
    Posts:
    90
    Code (csharp):
    1.  
    2. //put this in a script on the chair
    3. public void OnTriggerEnter(Collider col)
    4. {
    5.     if(col.transform.CompareTag("MyDudesTag"))
    6.     {
    7.         col.transform.parent = transform;
    8.         col.transform.localPosition = Vector3.zero;
    9.     }
    10. }
    11.  
    12. public void OnTriggerExit(Collider col)
    13. {
    14.     if(col.transform.CompareTag("MyDudesTag"))
    15.     {
    16.         col.transform.parent = null;
    17.     }
    18. }
     
    jorn818 likes this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    don't set the local position to zero... less you'd rather the object teleport to <0,0,0> of the chair when you enter its collider.
     
    jorn818 likes this.
  4. jorn818

    jorn818

    Joined:
    May 12, 2013
    Posts:
    97
    So there are some errors, and i'm used to using Javascript, so it seems almost akward to ask you to take a look xD
    It has something to do with Collider col

    ''A namespace can only contain types and namespace declarations'' on both line 2,13 and line 11,13