- Home /
Setting References (!Inspector)
How would I set references to scripts from inside a script? To clarify my problem, I have a gameObject. I'm instantiating it during runtime, and would like to have it access another script. However, I can't set references directly in prefabs, so I need a way to instantiate it with a reference, or maybe have it get a reference. Would I use gameobject.find
and then use a getcomponent
? Thanks a heap, and all help appreciated! (as in upvotes)
Answer by Eric5h5 · Apr 03, 2010 at 01:58 AM
It's not really possible to answer that definitively unless you say what other script you want to access and where it's located. Assuming that the script you want is attached to the same prefab as the first script and is called "AnotherScript", your first script would have something like:
private var aScript : AnotherScript;
function Start () { aScript = GetComponent(AnotherScript); }
But, like I said, it depends.
Edit: based on your comment, there's more than one way to do that. If there's just one object, you can do this:
private var aScript : Stock;
function Start () { aScript = GameObject.Find("Resources").GetComponent(Stock); }
Or this, if there's just one copy of the script:
private var aScript : Stock;
function Start () { aScript = FindObjectOfType(Stock); }
Or, for a different approach, you could make "clicked" on Stock a static variable:
// Stock.js
static var clicked : boolean;
That way you don't need to get a reference, and can set "Stock.clicked = true" from anywhere, at any time. Static variables are appropriate if there's only one of them in the entire game. You can use that to make Stock itself into a singleton:
// Stock.js var clicked : boolean; static var instance : Stock;
function Awake () { instance = this; }
Then, on other scripts, without having to get a reference, you can do this:
Stock.instance.clicked = true;
You can access any public variables or functions in Stock.js that way.
@Eric5h5 Well, what I'm trying to do is instantiate a prefab, and have it access a script on a gameObject called 'Resources'. There's only one gameObject called 'Resources', and only one script called 'Stock' in the game. I need to access it from a newly created gameObject so I can modify it, so if I enter a trigger, it sets 'Resources.clicked' to true... That's the gist of it anyway. Thanks for answering!
@elbon96: O$$anonymous$$, that makes things much clearer...I added some stuff to my answer.
@Eric5h5 BTW, bit late, but this line in your script: aScript = GameObject.Find("Resources").GetComponent(Stock);
needs to be this: aScript = GameObject.Find("Resources").GetComponent("Stock");
@elbon96: No, that would make it worse. Using GetComponent without quotes is preferable because it's faster and catches errors at compile-time ins$$anonymous$$d of run-time.
Your answer
![](https://koobas.hobune.stream/wayback/20220612143054im_/https://answers.unity.com/themes/thub/images/avi.jpg)