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

Getting a child GameObject with more than one components of that type / how to detach child object

Discussion in 'Scripting' started by ArrogantPride, Feb 21, 2016.

  1. ArrogantPride

    ArrogantPride

    Joined:
    Feb 11, 2016
    Posts:
    6
    So in my current game, I have a player, and upon the death of the player I would like there to be a camera around the place where they died. The normal FPS camera I use is attached to the player as a child of the whole player, and I have not found any way to detach that gameobject from its parent and leave it in the position that the player died.

    Also, how can you reference a child GameObject through the use of GetComponentInChildren<>() when an object has more than one object of the same type of component? For example, if it is impossible to detach the camera gameobject from the parent as mentioned earlier, I would include a second camera that is disabled until the player's death, and that second "death camera" would be a child of the player in the same way that the FPS camera gameobject is. So if I wanted to define that "death camera" in my HealthScript and have that script enable it upon the death of the player, how would I access this camera since
    a) It is disabled and
    b) There are more than one components of type Camera in children

    If anyone can help me out answering one or both of these questions I would immensely appreciate it.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,735
    Code (csharp):
    1. yourCamera.transform.SetParent(null);
    Code (csharp):
    1.  
    2. Camera[] allChildCameras = GetComponentsInChildren<Camera>();
    3. foreach (Camera thisCamera in allChildCameras) {
    4. //do something with thisCamera
    5. }
    Check the GetComponent(s)(InChildren) documentation - there is a variant that takes a parameter which includes inactive cameras.

    Also you could make a public variable and manually assign it.