Search code examples
c#unity-game-enginecomponentschildren

How to set prefab children's components on a script from inspector?


I am new to Unity!

I have a player prefab with this tree: Player tree Each item has a BoxCollider2D component

I also have a wall prefab with this script: Wall Script

What I want to do is set the collider of topCol as the Up Collider variable, the collider of downCol as the Down Collider variable and so on... I can't seem to figure out how to do it in the inspector, because it seems like I can only select the player prefab boxcollider2d component and not the children ones!

I am aware I can retrieve those components via script, I am just wondering if I can do it just via inspector!

Thank you for reading :D


Solution

  • Prefabs (unfortunately) don't work this way.

    • Because the player prefab gets instantiated, you want your walls to reference the instantiated player: not the prefab player!

    • Because your walls are also instantiated, it means that you can't reference scene objects (as they may not exist at the time the prefab gets instantiated)!

    As a result, you can only assign these fields at runtime through code.