From 2d281302b5d53fea855f67968f78dad18d2de5d5 Mon Sep 17 00:00:00 2001 From: Piero Dotti Date: Wed, 10 Apr 2024 21:05:22 +0200 Subject: [PATCH] docs(prefab): documenting component --- src/content/reference/components/prefab.md | 87 ++++++++++++++++++++++ src/sidebarReference.json | 4 + 2 files changed, 91 insertions(+) create mode 100644 src/content/reference/components/prefab.md diff --git a/src/content/reference/components/prefab.md b/src/content/reference/components/prefab.md new file mode 100644 index 0000000..0a8d965 --- /dev/null +++ b/src/content/reference/components/prefab.md @@ -0,0 +1,87 @@ +--- +title: +layout: API +--- + +`` allows to instantiate a custom prefab as a React Component. + + + +```js +export default function App() { + // Load the prefab using globals + const { prefab } = useGlobals(); + // or alternatively you can load the prefab from resources + // const prefab = useMemo(() => Interop.UnityEngine.Resources.Load('MyPrefab') as UnityEngine.GameObject, []); + + return ; +}; +``` + + + +### Lifecycle events and properties + +`` component instantiates the prefab, then searches for a component implementing the `IPrefabTarget` interface and calls the `Mount`, `UnMount` lifecycle hooks with the prefab instance. + +You can use them to handle custom logic, events, and properties passed to the prefab. + +#### Example of a custom prefab target component: +```csharp +public class MyComponentPrefabTarget : MonoBehaviour, IPrefabTarget +{ + PrefabComponent Component { get; set; } + + public Action AddEventListener(string eventName, Callback callback) + { + // Here you can handle custom events passed to the prefab. + return null; + } + + public void Mount(PrefabComponent cmp) + { + Debug.Log("Mounting MyComponentPrefabTarget"); + // Saving the reference of cmp to use it later + // For instance you can use it to emit custom events to React `Component.FireEvent("onSomething", value)` + Component = cmp; + } + + public bool SetProperty(string propertyName, object value) + { + // Here you can handle custom properties passed to the prefab + switch (propertyName) + { + case "myprop": + Debug.Log("Doing something with myprop"); + return true; + } + return false; + } + + public void Unmount(PrefabComponent cmp) + { + Debug.Log("Unmounting MyComponentPrefabTarget"); + Component = null; + } +} +``` + +##### Example of a prefab with a custom target component: +```js + +export default function App() { + const prefab = useMemo(() => Interop.UnityEngine.Resources.Load('MyPrefab') as UnityEngine.GameObject, []); + + return ( + console.log('Something happened', val)} + /> + ); +}; +``` diff --git a/src/sidebarReference.json b/src/sidebarReference.json index 55274aa..d9d14db 100644 --- a/src/sidebarReference.json +++ b/src/sidebarReference.json @@ -81,6 +81,10 @@ "title": "style", "path": "/reference/components/style" }, + { + "title": "prefab", + "path": "/reference/components/prefab" + }, { "title": "svg", "path": "/reference/components/svg"