- Home /
Injecting data into Prefabs
Hi,
I have a book that consists of pages. Each page has a prefab and some data associated with it. When you turn the page, the app will instantiate the next page's prefab (mostly textboxes), and then load the data into the instance, thus filling out the text.
// Create the cover page data
CoverPageData cpd = new CoverPageData( );
cpd.LocKey = "cover_page_text";
cpd.BtnLocKey = "start_btn_text";
cpd.BkgTexture = "title_page";
// Create the story page data
StoryPageData spd1 = new StoryPageData( );
spd1.LocKey = "page_1_text";
spd1.BkgTexture ="image_1";
StoryPageData spd2 = new StoryPageData( );
spd2.LocKey = "page_2_text";
spd2.BkgTexture ="image_2";
// Add pages to PageArr. Each page couples a prefab with data.
PageArr.add(new Page(CoverPagePrefab, cpd));
PageArr.add(new Page(StoryPagePrefab, spd1));
PageArr.add(new Page(StoryPagePrefab, spd2));
I want to keep things robust and data driven. I am new to Unity. Is this the best way to handle dealing with prefabs and data?
Is there an editor solution where I could be creating this same concept (not in code, but through editor gameobjects/prefabs instead)?
Thanks.
Answer by komodor · Jul 02, 2015 at 11:51 AM
i would make one prefab for each layout and create compoennt for each prefab type which will fill it with data, then you can just instantiate right prefab and fill it with data from your data source (text asset, xml, json)
other approach would be to create the text boxes by code, so you could have just one prefab with component which will recreate the layout and then fill it with data
or you can stay in the middle - one prefab with "layers" or container objects with layouts which are hidden while one of them is displayed with correct data
Thanks for your response, komodor.
"i would make one prefab for each layout and create compoennt for each prefab type which will fill it with data, then you can just instantiate right prefab and fill it with data from your data source (text asset, xml, json)"
This is the approach I would like to use, but the "fill it with data part" is the crux of my problem.
In the code above, I have an array and I am pairing a prefab with data to be loaded into it. I would like to do this in a data driven, editor way, ins$$anonymous$$d of in code.
Is there a way in the editor to have an array which pairs prefab and data?
Element 0:
Prefab: CoverPagePrefab
Loc$$anonymous$$ey: "coverPage"
Btn1Loc$$anonymous$$ey: "coverPageBtn1"
Btn2Loc$$anonymous$$ey: "coverPageBtn2"
Btn3Loc$$anonymous$$ey: "coverPageBtn3"
Element 1:
Prefab: StoryPagePrefab
Loc$$anonymous$$ey: "storyPage1"
Img: Page1Img
Your answer
Follow this Question
Related Questions
Runtime Changes to UI Object From Prefab Unexpectedly Changing All Prefab Objects 1 Answer
SetActive true not working on UI object 2 Answers
UIPrefab from prefab Canvas to live Canvas 1 Answer
Canvas with GUI elements in prefab act strangely 0 Answers
Display text above prefabs in Unity 4.6 0 Answers