Search Unity

GetComponentInParent reference

Discussion in 'Scripting' started by B-30, Jun 19, 2019.

  1. B-30

    B-30

    Joined:
    Nov 3, 2014
    Posts:
    28
    I have a script called "switcher" on the parent GO with a public bool called "end" and a starting value of "false". I want one child to set "end" to "true" and have all its siblings know that. I'm using GetComponentInParent and it works, but only if I *directly* address it every time like so on the child:
    Code (CSharp):
    1. if(someConditionOnChild) { gameObject.GetComponentInParent<switcher>().end = true; }
    and like so on the siblings
    Code (CSharp):
    1. if( gameObject.GetComponentInParent<switcher>().end == false ) {
    2.    //go ahead and do stuff
    3. }
    But if I try referencing it, like:
    Code (CSharp):
    1. public bool myEnd;
    2. public switcher mySwitcher;
    3. void Start ()
    4. {
    5.    mySwitcher = gameObject.GetComponentInParent<switcher>();
    6.    myEnd = mySwitcher.end;
    7. }
    8. void Update ()
    9. {
    10.    if(someConditionOnChild) {
    11.       myEnd = true;
    12. }
    13.    if(myEnd == false) {
    14.       //go ahead
    15. }
    it doesn't work.

    Any clues most appreciated.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    The issue is bools are value types, not reference types. You essentially are setting myEnd = to the value of mySwitcher.end. Which means it simply gets the value and applies that to the myEnd variable.

    If you want to change the parents value, you'll want to do it by accessing mySwitcher.end
     
  3. B-30

    B-30

    Joined:
    Nov 3, 2014
    Posts:
    28
    Of course! Thank you Brathnann, most appreciated.