This is a little difficult to explain so I’ll do my best… I have several of the same object with the same script, lets say ScriptA. From another script, ScriptB, I want to be able to call a function from ScriptA that will return the position of each of the objects in C#… Thank you.
You can use [Object.FindObjectsOfType()]. Note it is slow, so you don’t want to be using every frame, and it does not find inactive game objects.
ScriptA scripts = Object.FindObjectsOfType(typeof(ScriptA)) as ScriptA; for (int i = 0; i < scripts.Length; i++) Debug.Log (scripts*.gameObject.transform.position);*
If you want inactive game objects as well, see [Resources.FindObjectsOfTypeAll()]
: Unity - Scripting API: Object.FindObjectsOfType
: Unity - Scripting API: Resources.FindObjectsOfTypeAll
Take your time and read the whole thing, you will pick up an interesting thing from it.
Let’s say I would want to access variableA in ScriptA that is a component of object with name “IgorAherne”. I would like to trace a path to that script and store it in a shortcut variable _scriptA
ScriptA _scriptA; //we've declared a shortcut variable that can accept any value that is in the form ScriptA. _scriptA = GameObject.Find("IgorAherne").GetComponent("ScriptA"); //we search the object by name
After we found such object, ask the result of this search to continue the search in that GameObject, and search for ScriptA. It then searched in that object for the ScriptA.
After we’ve reached that Object’s ScriptA, we want to assign that ScriptA to our prepared shortcut variable. It is possible, since shortcut was declared with type ScriptA, remember?
now you can refer to the script with just mentioning our shortcut variable, _scriptA.
We will not be calling expensive function “Find” anymore, since the computer already found the script.
If you look back to the beginning, I wanted to access the variableA in that script.
I can do it like this:
accessing our defined script with shortcut variable and going inside it to access variableA. will only work if variableA actually exists in that ScriptA.
Finally, notice the following. I knew I was searching for a variable since the beginning. Why didn’t I continue the search up to the variable and assign it to shortcut?
Well, that wouldn’t have created a path to the script, but would only copy a VALUE of the variable into our shortcut. Ending the search on the place where there is no value available, such as on ScriptA means that you want to create a shortcut. otherwise you simply equalize the shortcut to the variable’s value.
And that wouldn’t work anyway, since in our declaration of shortcut, the shortcut was of type ScriptA, not the variable’s type whatever it would be (for example Int). the shortcut of type ScriptA couldn’t take the value of type int and we would get an error.