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

Instantiated GameObject child has a different parent GameObject

Discussion in 'Scripting' started by ddbrown30, May 19, 2020.

  1. ddbrown30

    ddbrown30

    Joined:
    May 19, 2020
    Posts:
    9
    I apologize for the confusing title. This one is a bit tough to summarize. Here's the long version.

    I have a script that spawns GameObjects based on a prefab (public GameObject PrefabObject). Here's the code:

    Code (CSharp):
    1.  
    2.         Canvas canvas = FindObjectOfType<Canvas>();
    3.         GameObject instObj = Instantiate(PrefabObject, canvas.transform);
    4.         MyOtherScript otherScriptComponent = instObj.GetComponentInChildren<MyOtherScript>();
    5.  
    With this code, the value of otherScriptComponent.gameObject is not pointing to instObj. For reference the value of instObject is "Name of Prefab(Clone)" and the one in the component is just "Name of Prefab." The (Clone) version is the one I see in the outliner. Any idea what's going wrong here?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    In your prefab, is the instance of MyOtherScript on the root GameObject of the prefab? Or is it on some child object? You're using GetComponentInChildren which implies to me it's not on the root object of the prefab. In which case the name will be whatever the name of that child is in the prefab, as Unity only appends the "(clone)" suffix to the root object name of the prefab.
     
  3. ddbrown30

    ddbrown30

    Joined:
    May 19, 2020
    Posts:
    9
    Yes, you're right. Never mind. I'm an idiot. The gameObject of the component is not the same gameObject as I'm instantiating as it's a child. They have similar names and my brain was not seeing the difference. Thanks for the help.
     
    PraetorBlue likes this.
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    No problem. You're not an idiot; sometimes you've just been staring at a problem for so long you need an outside perspective to see something obvious. It happens to everyone.