- Home /
Set a script as a variable in C#
I need a way to set a script as a variable in C#, like how one would use "public GameObject x," but I need a beginning part that would identify a script. If this is impossible, then I need a different way to make a script a parameter within a method. Any help is appreciated.
Answer by moltow · Jul 28, 2017 at 11:15 PM
Your script is a class, just like GameObject
is a class. Thus, you can do something like...
public MyClass myClassInstance;
void Start()
{
myClassInstance = GetComponent<MyClass>();
// This assumes you attached a MyClass component to this GameObject
}
If you have MyClass attached to a different GameObject, look at the docs related to GameObject.Find.
Answer by SteenPetersen · Jul 29, 2017 at 12:09 AM
you have not explained why you need this so perhaps you can also take a look at statics:
https://unity3d.com/learn/tutorials/topics/scripting/statics
I already use statics, but I have certain data saved within scripts around my folder that all correspond to a specific Item. When taking out an item, it needs to convert a supplied ID to a prefab that contains that ID, and the way that I've theorized doing this is through saving both the prefab and the ID to a script, and it could find the ID of ScriptX, and then use ScriptX.Prefab to instantiate it.