Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How to access data from another component? IE: Show your HP on screen

Discussion in 'Project Tiny' started by ElementalCode, Dec 8, 2018.

  1. ElementalCode

    ElementalCode

    Joined:
    Aug 6, 2014
    Posts:
    2
    Lets say your "Health" component knows how much HP you have. Now let's say I want to print that number on screen.

    I have a system that looks for the Text and then looks for the Data containing entity (player) and then prints the data.

    I got it working.

    But putting a for each inside a for each sounds like a performance killer :S

    Is this the correct way?

    Code (JavaScript):
    1.         OnUpdate():void {
    2.             this.world.forEach([ut.Text.Text2DRenderer,TagHPShow],
    3.                 (text) => {
    4.                     this.world.forEach([Health,TagPlayer],
    5.                         (data) => {
    6.                             text.text = Health.remaining + "/" + Health.total;
    7.                         });
    8.                 });
    9.         }
    Thinking in Systems is hard :(
     
  2. etienne_unity

    etienne_unity

    Unity Technologies

    Joined:
    Aug 31, 2017
    Posts:
    54
    Hi @ElementalCode

    One way to avoid the nested forEach would be to reference the Health entity from the TagHPShow entity, using an EntityReference field.
     
  3. raymondyunity

    raymondyunity

    Unity Technologies

    Joined:
    Apr 30, 2018
    Posts:
    97
    You can create a system ("ShowHPSystem") that would query all three components [health,tagplayer,taghpshow]. Add the EntityRefernce to your Health component to refer to the entity to change (the HP label). This will only run when you attach the TagHPShow along with the other components onto your entities. You can update text with the entity reference found in Health component.

    To extend this idea...
    You can even "drive/activate" it with another system, let's say "OnPlayerHit", add the TagHPShow component when a player is hit. Remove it after DMG is calculated and now you have a damage counter.