I can only adress the prefab of instantiated objects!

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:

public class GameSetup : MonoBehaviour
{
    GameObject Bird;
    List<GameObject> AllBirds;
    List<GameObject> BirdsInGame;

    private bool BirdsInstantiated = false;
   



    void FixedUpdate()
    {
        if (!BirdsInstantiated)
        {
            AllBirds = new List<GameObject>(Resources.LoadAll<GameObject>("Birds"));
            BirdsInGame = new List<GameObject>();

            for (int i = 0; i < 2 /*laterLevelNumber */; i++)
            {
                // Set the Position for the two birds somewhere Random.
                float xPosition = Random.Range(-1, 1);
                float yPosition = Random.Range(-1 / 2, 1 / 2);

                //Get a random number between 0 and the Length of the AllBirds List
                int randomBird = Random.Range(0, AllBirds.Count);

                //Instantiate the Object
                Instantiate(AllBirds[randomBird], new Vector2(xPosition, yPosition), Quaternion.identity);

                //Then, Remove this Object from the AllBirds List and add it to the BirdsInGame List
                BirdsInGame.Add(AllBirds[randomBird]);
                AllBirds.Remove(AllBirds[randomBird]);

            }

            BirdsInstantiated = true;

        }

Thank you so much!

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)


Thanks! That was a huge help. It's working now :)