- Home /
Access other script from Editor script
Hi, is it possible to access other script from Editor script (no the one It's editing). As i understand i can't use getcomponent or other "usual" methods.
Thank you very much.
I tried that already, but it still returns null reference.
I can't test this right now, but doesn't ((TypeOfTarget)target).gameObject
return the GameObject the target script is attached to?
Here's an example of what i would like to achieve, is it somehow possible ?
using UnityEditor;
using UnityEngine;
using System.Collections;
[ExecuteInEdit$$anonymous$$ode]
[CustomEditor(typeof(ScriptA))]
public class ScriptAEditor : Editor {
ScriptB b;
public override void OnInspectorGUI(){
b.function(); //call of get something
}
}
Please use a "comment" to reply rather than creating an "answer".
Answer by Jamora · Sep 08, 2013 at 06:04 PM
I was right in my comment. You just need to cast is as MonoBehavior.
If your ScriptB is attached to the same GameObject, just do what I told in my comment. If it's in a different gameObject, you can do GameObject.Find or the other usual ways.
ScriptB b;
void OnEnable(){
script = ((MonoBehaviour)target).gameObject.GetComponent<ScriptB>();
b.YourFunction();
}
Unfortunately, It's not attached to the same GameObject.
Any editor script should be in the editor folder, not attached to a gameObject.
How would you access your script normally then, from a non-editor class?
Yes, i found it. Posting for the record:
GameObject go = GameObject.Find("somegameobjectname");
ScriptB other = (ScriptB) go.GetComponent(typeof(ScriptB));
other.DoSomething();
Found it from here: http://answers.unity3d.com/questions/7555/how-do-i-call-a-function-in-another-gameobjects-sc.html
And as all of you still spend time replying, everyone gets a thumb up (;
Answer by onsboy · Aug 04, 2018 at 06:11 AM
I Would Like To Add That While **The Above Code IS Completely Correct.**Sometimes Unity Doesn't Update Properly and Still Throws Null Exception Error...
You can Also Write the Above Code Like This (As of Unity 2018.1.2f1):
GameObject go = GameObject.Find("somegameobjectname");
ScriptB other = go.GetComponent<ScriptB>()
other.DoSomething();
{NOTE : Don't Do GameObject.Find in Update Loop.It Can Slow Down Game...Just for the beginners out there}
In That Case Do A Couple OF things Which May Solve the issue :-
1. Make Sure You Are In Play Mode.
2. Clear The Cache.
3. Restart Unity (If necessary PC)