- Home /
How to use the Object class to pass a Vector2?
Hi all,
I'm working on a context menu to use within the Unity Editor(in a seperate window). I want to create a new window by pressing the Action button from the context menu and the window has to appear at the mouse position.
The problem is that I can't seem to pass the mouse position to the function which places the window. Here's part of the code I use:
menu.AddItem(new GUIContent("Action") , false, CreateActionBox, mousePos);
And this is the function(Which is passed in the 3rd argument in the menu.AddItem function) it executes when clicking the Action button from the context menu.
private void CreateActionBox(Object obj)
{
FieldWindow wind=new FieldWindow(1, new Rect(obj.x,obj.y,10f,10f));
FieldWindows.Add(wind);
Debug.Log("Window created");
}
The mousePos variable is a Vector2 but the only type to pass in the fourth argument in the menu.AddItem function is Object. I can't find out how to make unity treat the Object type as a Vector2.
The unity documentation describes a JS way to pass a String to the function but I can't translate it to a right C# way, there is no C# example in the documentation. Here's the similar code from the documentation in JS:
menu.AddItem (new GUIContent ("MenuItem1"), false, Callback, "item 1");
And:
function Callback (obj:Object) {
Debug.Log ("Selected: " + obj);
}
I have also tried different approaches such as:
private void CreateActionBox(Vector2 pos)
And casting the mouse position as Object but I didn't find a way that works.
I hope you can help me!
Answer by jctz · Jul 16, 2015 at 05:55 AM
did you try this?
private void CreateActionBox(Object obj) { Vector2 pos = obj as Vector2; FieldWindow wind=new FieldWindow(1, new Rect(pos.x,pos.y,10f,10f)); FieldWindows.Add(wind); Debug.Log("Window created"); }
Hey, thanks for your reaction.
I just tried:
private void CreateDialogueBox(Object obj)
{
Vector2 pos=obj as Vector2;
FieldWindow wind=new FieldWindow(1,new Rect(pos.x,pos.y,10f,10f));
FieldWindows.Add(wind);
Debug.Log("Window created");
}
But it results in the error:
error CS0077: The `as' operator cannot be used with a non-nullable value type `UnityEngine.Vector2'
Trying similar aproaches such as:
menu.AddItem(new GUIContent("Dialogue"),false,CreateDialogueBox,mousePos as Object);
Results in the error:
error CS0039: Cannot convert type `UnityEngine.Vector2' to `UnityEngine.Object' via a built-in conversion
Replacing it with casts also results in errors stating that it can not convert Vector2 to Object and neither the other way around.