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 How do I assign a prefab to a variable with code? (C#)

Discussion in 'Scripting' started by Lenticularic, Jul 12, 2021.

  1. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    How do I assign a prefab to a variable with code? I thought of instantiating the prefab, then assigning that instantiated prefab, but that just seems over complicated and messy. Is there a better way?

    I've seen other people ask this, but they are always in JavaScript, I'm using C#.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    That's the way.

    1. instantiate the prefab
    2. assign that to a variable.

    Where is the mess? Which part of the above do you wish to eliminate?
     
    Lenticularic and Brathnann like this.
  3. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    oh, thanks.

    I thought the way was roundabout, like an extra step. I didn't know that there wasn't a way just to get it from the project files.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    The reason you can't just get it from the project files is that it doesn't exist until you call Instantiate<T>(). :)
     
  5. Lenticularic

    Lenticularic

    Joined:
    Nov 16, 2020
    Posts:
    46
    Ohhhh, I never new that. thanks for saying.