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

C# - RayCast - SetParent

Discussion in 'Scripting' started by bigboybifdick, Mar 9, 2015.

  1. bigboybifdick

    bigboybifdick

    Joined:
    Feb 8, 2014
    Posts:
    60
    Hi Guys,

    I'm trying to build a "Pull/Push" mechanism.
    The way i'm doing it right now, is to make the player the parent of the Gameobject the User Click On.
    Here is my code :

    Code (CSharp):
    1.  
    2.  
    3. public GameObject myPlayer;
    4.  
    5. voidUpdate(){
    6.  
    7. if (Input.GetMouseButtonDown (0)) {
    8. Rayray = GetComponent<Camera> ().ScreenPointToRay (Input.mousePosition);
    9. RaycastHit hit;
    10.  
    11. if (Physics.Raycast (ray, out hit) && hit.transform.parent == myPlayer.transform) {
    12. hit.transform.SetParent (null);
    13. Debug.Log("SetParentToNull");
    14.  }
    15.  
    16. if (Physics.Raycast (ray, out hit) && hit.transform.parent == null) {
    17. hit.transform.SetParent (myPlayer.transform);
    18. Debug.Log("SetParent");
    19.  
    20.  }
    21.  
    22.  } }
    23.  
    But this is not working. I don't really get why.
    Each part work independently (setting a gameobject as a child of the myPlayer GameObject, or setting his parent to null). But they stop working as soon as they are together...

    What am i missing ? :D

    Thanks a lot !
     
    Last edited: Mar 9, 2015
  2. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    I assume you also get an error in the console? Post that here too, as currently I can only guess for the error which would be that you create a local field for the hit called 'hit' and use a field called 'outhit' in the raycasts. Changing that to 'hit' should work
     
  3. bigboybifdick

    bigboybifdick

    Joined:
    Feb 8, 2014
    Posts:
    60
    Hey Timelog,

    Thanks for the answer.
    My bad, a space was missing between Out and Hit, i've edited my code in the previous post.
    I don't have any error in the console.

    When i click a Gameobject, it becomes a child of myPlayer.
    When i click again i can see the Debug.Log("SetParentToNull"), but nothing happens:

    hit.transform.SetParent (null); doesnt seem to work.


    SOLVED WITH AN ELSE. SORRY.
     
    Last edited: Mar 9, 2015