Search code examples
unity-game-engine

How can I assign Game Object from scene to prefab in Unity?


I'm kinda new to Unity and to programming overall and I tried to make a game on my own, but i ran into problem that I don't know how to fix. So, in order for my code to work, I need to assign scene called "Player" to prefab target as you can see on the image:

Image

But I found out, that you cannot do that in Unity with prefab as it always shows error that it's Type mismatch:

Image

I tried methods like Find.Object(), but I could't make it work. Is there any other way I can assign "Player" to the prefab "Target" or do I must try some other way? Thank you in advance for your reply


Solution

  • The short answer is: You don't!

    For sure there are ways and edge-cases where you can use a workaround. But what would be the purpose of that in your use case?

    As soon as the scene gets unloaded (switched to another scene or the editor closed), your scene objects do not exist anymore.

    The next time you open the scene these are new instances so the link to the prefab is lost. That's why the Inspector right away makes it impossible to reference scene instances in assets.


    Now I know of course where you wanted to go with this but to do this properly and the c# way:

    • Something in your scene (let's just call it EnemySpawner) is spawning the enemies into your scene.
    • So that EnemySpawner is a scene object and thereby very well can have a reference to your other scene objects such as your player.
    • So that everytime it instantiates a new enemy instance into your scene it can also simply pass along that player reference to the newly spawned enemy instances.

    I would discourage from things like

    • Find because it uses hard coded strings which easily breaks, is horrible to maintain and slow
    • FindObjectOfType/FindFirstObjectByType/FindAnyObjectByType because they always assume some sort of singleton instances and introduce hidden and hard to maintain dependencies

    With the above approach via the EnemySpawner on the other hand you have a clear visible dependency. The EnemySpawner needs a reference to the (current) player instance. And it also has a clear way of passing that dependency further to the enemy instances itself creates (and evtl maintains - e.g. ObjectPooling etc)