Search Unity

Assign prefab programmatically

Discussion in 'Scripting' started by IngeJones, Jul 25, 2017.

  1. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    I have read the "similar questions" that popped up below after I wrote my title, but while the question seemed straightforward, none of the posters seemed particularly satisfied with the answers, and I must admit I found them confusing too, so I will try posting myself and see if that gives me anything more straightforward.

    Ok, currently I have declaration lines that go like:
    public GameObject ActorPrefab;
    private static GameObject staticActorPrefab;
    in Awake() I have
    staticActorPrefab = ActorPrefab;

    I drag my prefab onto the ActorPrefab slot in the Editor. But I use it from the static reference all through my game.

    My question is, what is the right/best/simplest way to simply assign the prefab directly to the static variable for it (using c# code presumably) thereby losing the "public GameObject ActorPrefab;" line?
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    The simplest way would be to use Resources.Load.

    The right way would probably involve not using static at all.
     
  3. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Thanks. Yeah I know there is some controversy about static classes and fields - spent part of the weekend reading discussions about singleton.v.static. This is indeed code on a game controller type of class (not my main gamecontrol object which *is* an instance, but a helper management class. I just get tired of typing "Somecontroller.Instance.Whatever" when I could just type "Somecontroller.Whatever" lol.
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Nothing says you can't use a pure static method and hide the singleton implementation.
     
    IngeJones likes this.
  5. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Well I couldn't use a static method and reference the public editor variable from it, that's why I used the workaround of casting it to a static variable at runtime. But it irritates me to have two references to the same object in the same instance!
     
  6. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,532
    There's not really a magical tidy way around this and the way you're handling it is (imo) acceptable. You can null the exposed variable after assigning the static one if you're that worried about the pointer sticking around.

    Is there a performance concern here or is it just an exercise to clean up?
     
    IngeJones likes this.
  7. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Lol you're right, I am a cleanup freak :D No it wasn't causing a problem