Forum Discussion

Pastew's avatar
Pastew
MHCP Partner
1 year ago
Solved

How to access Methods and Properties of a referenced Entity in TypeScript (Desktop Editor)

Hi, I have two local scripts SomeLocalItem.ts AnotherLocalItem.ts SomeLocalItem has reference to Entity with AnotherLocalItem. I want: 1) Inside SomeLocalItem invoke method on referenced Anot...
  • Pastew's avatar
    1 year ago

    Thanks!

    Now I understand, it works if the player already owns both entities. Example below

    import * as hz from 'horizon/core';
    import { AnotherLocalItem } from 'AnotherLocalItem';
    
    // This script is set as Local
    class SomeLocalItem extends hz.Component<typeof SomeLocalItem> {
      static propsDefinition = {
        anotherLocalItemEntity: { type: hz.PropTypes.Entity }
      };
    
      start() {
        this.connectCodeBlockEvent(this.entity, hz.CodeBlockEvents.OnGrabStart, (isRightHand: boolean, player: hz.Player) => {
          this.entity.owner.set(player);
          this.props.anotherLocalItemEntity!.owner.set(player);
    
          // This will not work!
          // const anotherLocalItem = this.props.anotherLocalItemEntity!.getComponents(AnotherLocalItem)[0];
          // anotherLocalItem.printToConsole('Hello from SomeLocalItem');
        });
    
        this.connectCodeBlockEvent(this.entity, hz.CodeBlockEvents.OnButton1Down, () => this.onButton1Down());
      }
    
      onButton1Down() {
        const anotherLocalItem = this.props.anotherLocalItemEntity!.getComponents(AnotherLocalItem)[0];
        anotherLocalItem.printToConsole('Hello from SomeLocalItem');
        console.log('SomeLocalItem.onButton1Down: Level read from anotherLocalItem: ', anotherLocalItem.level);
      }
    }
    hz.Component.register(SomeLocalItem);