Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Help With Assigning Player To Prefab

Discussion in '2D' started by IrocJeff, Aug 2, 2020.

  1. IrocJeff


    Sep 13, 2019
    I'm running into a problem when it comes to prefabs and assigning my "player" as a GameObject or Target. Lets use my turret for example. I have one sprite as the turret and it has its script on it. Then, I have a shootpoint as a child object which has a script that does the firing.

    When I make this in game in works flawlessly. However, when I go to save this as a prefab so I can spawn them in game is where the issue comes in. My turret will spawn after it is triggered at its spawnpoint but it will not have my "player" as the turrets target. When I go into its range it says "game object not assigned" or similar.

    When I double click the prefab to go to what I assume is a prefab editor I cannot access my Hierarchy to select my player and drag in because once I go to hierarchy I close out of prefab editing. My other values stay there like Time Between Shots or my Bullet prefab, but for whatever reason, my "player" always gets removed.

    Is there any way around this?
  2. Derekloffin


    Mar 14, 2018
    I assume player is part of the scene and not part of the prefab (that would make sense). If so, the answer is no. Instead what you have to do is you have to set it up in script. There is a fair number of ways to do this:
    1. You can have the script for the prefab object look through all the scene objects for your Player object in start(). Assuming it is tagged appropriately, you can use that to detect such. If you scene is pretty complex this may be a bit slow, but so long as the scene is simple, or you're only doing it occasionally this can be fine. This is a relative thing as to actually notice you'd need a REALLY complex scene with lots of dynamic spawning going for it to matter usually.
    2. You can have another script or class somewhere where you can set the player object as a static and then replace your prefab's use of the local player pointer to use this static instead. If you have lots of different things referencing your player this may be a good way to go.
    3. You can invert 1 and have another object do essentially the same thing, but outside of the prefab's script (this is most often done by things like enemy spawners and such). This can be a bit faster and why it is used for spawners so that each spawn doesn't need to hunt down the player object.
    4. And of course you can just set it manually if you're just discretely creating the objects from prefab manually.