- Home /
referencing a script cheaply and efficiently
Hi, how do you reference a script without using GetComponent as I heard from an experienced programmer it's very labour intensive.
Searched in unity script reference and was hoping to find something like "Script" so I could reference it publicly.
What methods are there out there for doing this?
There's are not other ways that I know of but ideally just do GetComponent() once and cache it.
yes, generally that's the best place for those expensive, once-off things.
Answer by ZenithCode · Aug 28, 2013 at 12:42 PM
There's are not other ways that I know of but ideally just do GetComponent() once in Awake() and cache it.
Answer by perchik · Aug 28, 2013 at 02:53 PM
You could avoid the GetComponent() all together and just make a public variable of that type, then drag the GameObject with that script to it in the inspector.
yeah I did try that but then accessing the gameobject sub components such as it's attached scripts and being able to use them didn't seem to work without using GetComponent again. I wonder if i'm doing that wrong so might have a play with it tonight.
Do you have an example by any chance?
probably better if you post your code so the community can comment/advise accordingly...
back to the keynote ;)
@perchik's approach will work, but I just wanted to throw in that it's almost always better to connect references programmatically (like @ZenithCode suggests) rather than manually dragging to public variables. If you use a public variable, then if you change the referenced script, or if your component's metadata changes, you have to manually reassign the variable. If you call GetComponent once in Awake, you don't need to worry about this.
Your answer
![](https://koobas.hobune.stream/wayback/20220613113134im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
(Yet another) Accessing array in another script - ref or copy? 1 Answer
Reference script on Behaviour is Missing, but IT'S NOT MISSING 0 Answers
Getting UnassignedReferenceException even though reference assigned 1 Answer
What's the best way to store a reference to a script asset? 2 Answers
Need help with a raycast 1 Answer