- Home /
Is there a way to reference a script with a string?
using pragma strict I would like to reference a script before it is attached to anything by using a string that the user passes in.
In other words convert a string into a monoBehavior reference?
Is there a way to do that?
Thanks,
you should mention you need to do this in strict mode. :)
Answer by CHPedersen · Feb 27, 2012 at 08:41 PM
There is. You can try to call the version of GetComponent that takes a string argument:
http://unity3d.com/support/documentation/ScriptReference/GameObject.GetComponent.html
If you don't know which gameobject the required script is attached to either, you'll have to get a list of all gameobjects using this method:
Passing in GameObject for the type you're searching for, and then call GetComponent for the required script on each of them one by one.
Like so, it is technically possible, but please note that I don't recommend doing it. It's just too errorprone, and makes for inelegant code, besides. One should always use the generic version of GetComponent instead of the string version, where possible, and besides, searching for a script this way is not likely to be efficient, in case you need to do it on a frame-by-frame basis.
Sorry I wasn't too clear. I meant access the script using a string before it's attached using AddComponent. Is that possible.
What are you accessing if the script isn't attached to the object?
his previous question gives some context, this one is follow-up... http://answers.unity3d.com/questions/221685/pragma-strict-problem-with-getcomponent-and-script.html
WillTAtl: Thanks for adding that link to make things clearer.
Your answer
Follow this Question
Related Questions
Assign a reference to a Monobehaviour 1 Answer
Accessing a script only using its string 3 Answers