|
| 1 | +--- |
| 2 | +title: Extending ReactUnity |
| 3 | +--- |
| 4 | + |
| 5 | +<Intro> |
| 6 | + |
| 7 | +Extending ReactUnity |
| 8 | + |
| 9 | +</Intro> |
| 10 | + |
| 11 | +## Declaring custom components |
| 12 | + |
| 13 | +You can declare custom components in ReactUnity. This is useful when you want to create a component that needs to interact with the underlying backend (`ugui` or `uitoolkit`). |
| 14 | + |
| 15 | +To declare a custom component, you need to create a new class extending `UGUIComponent` or `UIToolkitComponent` and register it in `UGUIContext.ComponentCreators` or `UIToolkitContext.ComponentCreators` respectively. |
| 16 | + |
| 17 | +### Example |
| 18 | +First we create the custom component. For instance, we are declaring a custom button component that has a red background color. |
| 19 | + |
| 20 | +```cs |
| 21 | +using ReactUnity.Styling; |
| 22 | +using ReactUnity.UGUI; |
| 23 | +using UnityEngine; |
| 24 | + |
| 25 | +public class CustomButtonComponent : ButtonComponent |
| 26 | +{ |
| 27 | + public CustomButtonComponent(UGUIContext context, Color backgroundColor) : base(context) |
| 28 | + { |
| 29 | + Style[StyleProperties.backgroundColor] = backgroundColor; |
| 30 | + } |
| 31 | +} |
| 32 | +``` |
| 33 | + |
| 34 | +Then we need to register this component in `UGUIContext.ComponentCreators` dictionary. This can be done in a `MonoBehaviour` that is attached to the same `GameObject` as `ReactRendererUGUI` component. |
| 35 | +The declaration must be done before `ReactRendererUGUI` is enabled. |
| 36 | + |
| 37 | +```cs |
| 38 | +using ReactUnity.UGUI; |
| 39 | +using UnityEngine; |
| 40 | + |
| 41 | +public class CustomComponentInitializer : MonoBehaviour |
| 42 | +{ |
| 43 | + public ReactRendererUGUI reactUnity; |
| 44 | + public Color customButtonColor; |
| 45 | + |
| 46 | + void Start() |
| 47 | + { |
| 48 | + UGUIContext.ComponentCreators["customButton"] = (type, text, context) => new CustomButtonComponent(context, customButtonColor); |
| 49 | + |
| 50 | + reactUnity.enabled = true; |
| 51 | + } |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +### Typescript declaration |
| 56 | +You may also need to declare your custom component in Typescript |
| 57 | + |
| 58 | +```ts |
| 59 | +declare global { |
| 60 | + interface ReactUnityCustomElements { |
| 61 | + mycomponent: { myprop?: number }; |
| 62 | + } |
| 63 | +} |
| 64 | +``` |
| 65 | + |
| 66 | +#### Example: |
| 67 | +```ts |
| 68 | +declare global { |
| 69 | + interface ReactUnityCustomElements { |
| 70 | + button: Button; |
| 71 | + } |
| 72 | +} |
| 73 | +``` |
0 commit comments