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(); (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)
Looks right to me. You can shorten to: GetComponent() for the record. Hope ya find it.
2 Likes
Ok thanks then, I will look for some other cause of the problem 
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.
1 Like
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.
I’m glad that you solved it, anyways. Though, I agree something must’ve been amiss, because it should have worked, either way. 