- Home /
How to reference an EditorWindow script in a MonoBehaviour script OR how to pass variables from a EditorWindow to a MonoBehaviour script?
Hello, I am right now trying to build an EditorWindow from which I can activate my boosters, it works very simple, if I click the button on the EditorWindow the bool gets set too true.
Now I want to pass the bool variable to my playerMovement script, a MonoBehaviour script normally I would just reference the script where I set the bool variable, but I can not attach the editor window script to the playerMovement script, after some time googling I saw that you can't reference an EditorWindow script inside a MonoBehaviour script.
So how I do pass a bool variable from the EditorWindow to the PlayerMovement script?
My EditorWindow looks like this:
public bool speedBooster;
[MenuItem("My Windows/BoosterWindow")]
static void Init()
{
boosterWindow window = (boosterWindow)EditorWindow.GetWindow(typeof(boosterWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label("Active the boosters from the buttons below");
if (GUILayout.Button("SpeedBooster"))
{
speedBooster = true;
}
}
And my playerMovement will use the variable like this:
public class PlayerMovement : MonoBehaviour
{
public boosterWindow bw;
private void Update()
{
if (bw.speedBooster)
{
boosting = true;
speed -= 5;
}
}
}
Can anybody suggest me an idea of how I can tell the playerMovement script that the bool is true so that the speed variable gets changed?
Answer by trannel · Jan 02, 2021 at 07:51 PM
Dont reference Editor windows in monobehaviour its the wrong way around.
..
It looks like you do not want an Editor Window though. just an Editor.
an Editor class has a target
property (the monobehaviour).
usage:
[CustomEditor(typeof(PlayerMovement))]
public class PlayerMovementEditor : Editor {
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("boost player"))
{
Debug.Log((PlayerMovement)target);
((PlayerMovement)target).speedBooster = true;
}
}
}
if you realy want/ have to to use an EditorWindow, you will have to find the target monobehaviour. using e.g https://docs.unity3d.com/ScriptReference/Transform.Find.html or https://docs.unity3d.com/ScriptReference/Selection-gameObjects.html or many other ways.
Thank you very much, this way I could figure it out! I am a bit sad that it is not possible the way I wanted it to be, I thought having all boosters in a separate window would make it easy to test them out without needing the player to pick them up in the world. But Now I can just active them on the playerscript which is fine too :)