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

Question Error when passing a reference to a prefab being instantiated in script

Discussion in 'Scripting' started by tk421ad, Aug 9, 2023.

  1. tk421ad

    tk421ad

    Joined:
    Aug 7, 2021
    Posts:
    4
    I need help. I've come across an error. The goal is to instantiate a prefab, and give it a reference to a infoHolder script attached to a separate gameobject. the script that is instantiating the prefab has a reference to the InfoHolder script called infoholder as you'll see. There is a script on the prefab object called prefabManager, which has a reference to a public infoHolder. Here's the script:
    Code (CSharp):
    1. public InfoHolder infoholder;
    2.     public GameObject prefab;
    3.     public Vector3 pos;
    4.     public void start()
    5.     {
    6.     prefabManager prefabManagerInstance;
    7.         prefabManagerInstance = Instantiate(prefab, pos, Quaternion.identity) as prefabManager;
    8.         prefabManagerInstance.EI = infoholder;
    9.     }
    The code won't compile and I can't make any sense of the console error. If anyone could help it would be very much appreciated. Thank you in advance!
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Helps to tell us what the error is, and where the error is.
     
  3. tk421ad

    tk421ad

    Joined:
    Aug 7, 2021
    Posts:
    4
    The error is CS0165 but reading the docs it doesn't seem like it has anything to do with what I'm trying to do. Thank you for replying
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    Post the full error, please. And, again, what particular line of code it's happening at.
     
  5. tk421ad

    tk421ad

    Joined:
    Aug 7, 2021
    Posts:
    4
    I actually figured it out but thanks anyway
     
  6. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    You can't "cast" the GameObject Instantiate returns to a script component. You have to use GetComponent<>():
    Code (CSharp):
    1. var prefabManagerObject = Instantiate(prefab, pos, Quaternion.identity);
    2. var prefabManagerInstance = prefabManagerObject.GetComponent<PrefabManager>();
    3. prefabManagerInstance.EI = infoholder;