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

Question How to Get Components from an Instantiate object

Discussion in 'Scripting' started by Tatavasyon, Dec 27, 2022.

  1. Tatavasyon

    Tatavasyon

    Joined:
    Jul 14, 2022
    Posts:
    2
    Hello everyone,

    I can't to call components in instantiate object. I tried this way, but it doesn't work. I need help.

    Code (CSharp):
    1. public class islandStartPoint : MonoBehaviour
    2. {
    3.     public Transform startPoint;
    4.     public GameObject islandObject;
    5.     private Renderer _renderer;
    6.  
    7.     void Awake()
    8.     {
    9.         Instantiate(islandObject, startPoint.position, startPoint.rotation);
    10.     }
    11.     void Start()
    12.     {
    13.         Component[] islandObject;
    14.  
    15.         islandObject = GetComponentsInChildren(typeof(Renderer));
    16.  
    17.         if (islandObject != null)
    18.         {
    19.             foreach (Renderer islandChild in islandObject)
    20.                 Debug.Log("asd");
    21.         }
    22.     }
    23. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Your current code is trying to get components from YOURSELF, not the object you instantiated.
    Code (CSharp):
    1. GameObject instance = Instantiate(prefab);
    2. Renderer[] renderers = instance.GetComponentsInChildren<Renderer>();
     
    Tatavasyon likes this.
  3. Tatavasyon

    Tatavasyon

    Joined:
    Jul 14, 2022
    Posts:
    2
    This worked. It was hard for me but i understand now. Thank you so much.