Search Unity

Interaction between two script components added to an object at runtime

Discussion in 'Getting Started' started by CGEworks, Feb 23, 2017.

  1. CGEworks

    CGEworks

    Joined:
    Dec 16, 2013
    Posts:
    12
    edit: Thanks guys, GetComponent worked fine. As soon as you mentioned it I had a "Doh!" moment.

    So I’m a beginner / hobbyist dev, and I’m attempting to build a character/unit generator.

    The plan is to have baseStats (strength, constitution etc) as one component and healthPoints would be its own component, and those components would be added to the game object at runtime by the character generator script.

    The issue I’m having is that I want a value in one component (units healthPoints) to be derived from a value in another component (units constituionStat). But I’m getting a compile error in my healthPoints script because the component I’m trying to reference hasn’t been added yet…

    I know I could just combine the two components, but I also want non-unit objects to have healthPoints (doors, itemchests etc).

    And because I’m aiming for an ECS structure, I’m thinking that this issue of interactions between components is going to be something I’m dealing with a lot.

    This seems like the sort of issue that’d come up a lot so I wanted to ask: is there was a common / sensible way handling this?

    And bonus question: Is this the sort question I could post on Unity Answers or is it too open ended?


    Thanks!
     
    Last edited: Feb 25, 2017
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    The easy (and common) way to handle this is to simply get a reference to the other script via GetComponent<OtherScriptType>(). Generally you'd call this in Awake or Start, and store the result in a private property. (For scripts added dynamically, Start is probably better — Awake is called from the constructor, but Start is called later, before the next frame after the component is added.) Then you can get to any public properties or methods via that stored reference.
     
    Last edited: Feb 23, 2017
    CGEworks and Kiwasi like this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Note that this shouldn't give you a compiler error. It should give you a runtime error.

    If you are getting a compiler error its something else.