Set the Sprite for a child of a prefab before intstantiation.

I seem to be a bit stumped, I’m hoping you guys might have a better solution or a working one for that matter.

I have a preFab, that is not placed on my scene. I have an empty game object on my scene. Attached to the empty game object is a C# Script. I’ve declared a public variable for my preFab, and dragged it into the inspector.

The problem I’m having is this preFab has 4 children. The Prefab is a rectangle and the children are doors in the middle of each face (north door, south door, east door, west door).

In my C# script, I need to disable/enable the SpriteRenderer component of the child objects BEFORE I instantiate it. I’m using the following method, I’m trying to iterate through the preFabs children, but the loop is never entered.

Is this becuase the prefab isn’t instantiated, so I cannot access the components of it?

	private void SpawnDungeon() {
     roomCount = 0;
     doorsToSpawn = Random.Range (0,5);
     roomsToSpawn = Random.Range (minRooms - 1, maxRooms + 1);

                // This is what I'm trying to fix.
		SpriteRenderer[] rs = RoomPre.GetComponentsInChildren<SpriteRenderer>();
        foreach (SpriteRenderer r in rs) {
 		 Debug.Log ("We are inside the loop");

I’ve tried a few different things here, and Debug.Log is never called!

Is there another way I should go about this? Basically what I need to do is, enable the sprite renderer of each door, depending if that door should show. This needs to be done before the RoomPre is instantiated.

This is for procedural generation. Should I just use Resource.Load to grab the prefab rather than assigning it as a public variable? Would that allow me to edit the sprite renderers of the children objects of the prefab?

Thanks for your time,

JayOhh Games

I found the answer, stupid me. I didnt know what to search on here but I found it afterall.

I just needed to put true into the brackets of the get component.

        SpriteRenderer[] rs = RoomPre.GetComponentsInChildren<SpriteRenderer>(true);

Apparently doing that allows Unity to grab the non instantiated prefab and pull its children components! Man I feel stupid, such an easy fix.

if you only have 4 doors you could just run a for loop.

for(int i = 0; i < 5; i++)
    rs*.enabled = false;*

//Then here re-enable the doors that need to be there.