Search Unity

I can only adress the prefab of instantiated objects!

Discussion in 'Prefabs' started by killerflip, Jun 27, 2022.

  1. killerflip

    killerflip

    Joined:
    May 26, 2022
    Posts:
    11
    Hey everyone!

    I want to Instantiate 2 random game objects from my game object list. However in the game, I can't address the components of my instantiated objects that are now in my game, but only the components of my Prefab. That's turning into further problems down the road, e.g. I can't address the Audio Source of the instantiated object, but only the one from its prefab. Do you know what I'm missing? Here is my code for the Instantiation Process:

    Code (CSharp):
    1. public class GameSetup : MonoBehaviour
    2. {
    3.     GameObject Bird;
    4.     List<GameObject> AllBirds;
    5.     List<GameObject> BirdsInGame;
    6.  
    7.     private bool BirdsInstantiated = false;
    8.    
    9.  
    10.  
    11.  
    12.     void FixedUpdate()
    13.     {
    14.         if (!BirdsInstantiated)
    15.         {
    16.             AllBirds = new List<GameObject>(Resources.LoadAll<GameObject>("Birds"));
    17.             BirdsInGame = new List<GameObject>();
    18.  
    19.             for (int i = 0; i < 2 /*laterLevelNumber */; i++)
    20.             {
    21.                 // Set the Position for the two birds somewhere Random.
    22.                 float xPosition = Random.Range(-1, 1);
    23.                 float yPosition = Random.Range(-1 / 2, 1 / 2);
    24.  
    25.                 //Get a random number between 0 and the Length of the AllBirds List
    26.                 int randomBird = Random.Range(0, AllBirds.Count);
    27.  
    28.                 //Instantiate the Object
    29.                 Instantiate(AllBirds[randomBird], new Vector2(xPosition, yPosition), Quaternion.identity);
    30.  
    31.                 //Then, Remove this Object from the AllBirds List and add it to the BirdsInGame List
    32.                 BirdsInGame.Add(AllBirds[randomBird]);
    33.                 AllBirds.Remove(AllBirds[randomBird]);
    34.  
    35.             }
    36.  
    37.             BirdsInstantiated = true;
    38.  
    39.         }

    Thank you so much!
     
  2. jbnlwilliams1

    jbnlwilliams1

    Joined:
    May 21, 2019
    Posts:
    267
    I'm a newbie, but I believe you need to assign the instantiated prefab to an object. Such as ;

    Bird = Instantiate(AllBirds[randomBird], new Vector2(xPosition, yPosition), Quaternion.identity);

    I do believe that the instantiate function returns an object. You can then reference any component on the instantiated object.

    See here: Unity - Scripting API: Object.Instantiate (unity3d.com)
     
  3. killerflip

    killerflip

    Joined:
    May 26, 2022
    Posts:
    11
    Thanks! That was a huge help. It's working now :)