- Home /
How To Get Array From A Script That Isn't On A Gameobject (In Assets)
I have a script for the structure of a network, I am trying to get an array from it. How do I access the array from another script which is on a gameobject.
"How to get array from a script that isn't on a Gameobject ?"
"How do I access the array from another script which is on a Gameobject?"
What!?
Answer by Vicarian · Sep 05, 2017 at 05:48 PM
If the script describing the structure of a network is just an asset, and isn't itself on a GameObject, you may make the member you need static, such that it doesn't require an instance of the script to retrieve:
public class NetworkDescriptorClass {
// presumably a string array
public static string[] myDescriptionArray = new string[] { "Some Description", "Some other description", "etc" };
}
Then on the GameObject, do something with the data:
public class ExampleClass : MonoBehaviour {
void Awake() {
foreach (string s in NetworkDescriptorClass.myDescriptionArray)
Debug.Log(s);
}
}
It's not immediately clear that this will work to a beginner (presumably), but when you open your project in Unity, MonoDevelop project or Visual Studio solution files get generated. Any C# script existing in the project is added to the MonoDevelop project or the Visual Studio solution automatically. This exposes the symbols (the names of variables you create in scripts) to a symbol table that is interpreted eventually by the .NET Framework as the 1s and 0s that drive computer programs. I'm glossing over a bunch of the finer details to keep the explanation from getting too technical. Bottom line, this exposure allows your MonoBehaviour scripts to "see" and retrieve the value of other variables, especially static ones, elsewhere in the project, even if they're not attached to GameObjects.
Your answer
Follow this Question
Related Questions
Can I safely put a prefab asset into version control with Unity Free? 3 Answers
Save procedural mesh in the editor as asset. 2 Answers
AssetDatabase.ExportPackage not working 3 Answers
Ho do I find all scenes with a certain script on an GameObject 2 Answers
A event on deletion of asset in the asset database? 1 Answer