Search Unity

Finding a panel's CanvasGroup in C#

Discussion in 'UGUI & TextMesh Pro' started by IngeJones, Apr 8, 2017.

  1. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    I have a panel. The panel has a canvasgroup component and a script component (among others)

    From my script component, a line in Awake() says:
    myCanGrp = gameObject.GetComponent<CanvasGroup>(); (obviously myCanGrp is pre-declared)




    Yet after that, references to myCanGrp are still erroring as unassigned Is this not the right approach in theory to finding and assigning a canvasgroup component? (If it is, then I know to look for other syntactical or logic flow errors, so don't worry about offering to look at my entire script)
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Looks right to me. You can shorten to: GetComponent<CanvasGroup>() for the record. Hope ya find it.
     
    Salifya133 and IngeJones like this.
  3. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Ok thanks then, I will look for some other cause of the problem :)
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  5. UziMonkey

    UziMonkey

    Joined:
    Nov 7, 2012
    Posts:
    206
    Is the CanvasGroup on the same object as this script, or another object? To avoid things like this I usually just declare a public CanvasGroup in the script and assign the reference in the editor. That way you don't even have to find it in Awake, just drag the CanvasGroup component in the inspector and it's already there for you.

    But if the CanvasGroup is not on this object and rather on an object higher up, you can use something like GetComponentInParent. That will search upward through the hierarchy to find a component with that type.

    And finally you don't need to say gameObject.GetComponent, you can just say GetComponent. It's the same thing but with less typing.
     
    Salifya133 likes this.
  6. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Both components siblings on the same object (a panel) :) Well I fixed it by making the variable public and dragging the canvasgroup onto it in the inspector, but I can't help thinking that shouldn't have been necessary - I must have missed *something* I was doing wrong script-wise.
     
  7. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I'm glad that you solved it, anyways. Though, I agree something must've been amiss, because it should have worked, either way. :)