How to determine class of object at mouse position
Hello!
I have a class ("foo" say), and when I obtain a reference to a game object at my mouse position I want to determine whether the object is of the foo class. I obtain the object with
GameObject objAtMouse = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(mousePos), Vector2.zero).transform.gameObject;
where mousePos is the position of my mouse, and it seems to be working as intended. To test for class I have tried the following:
if(objAtMouse is foo){...}
foo fooAtMouse = objAtMouse as foo; if(fooAtMouse){...}
if ((objAtMouse.GetComponent("foo") as foo) != null){...}
Option 1. was suggested here and is the only one which does not produce an error, but yields the warning
The given expression is never of the provided ('foo') type
Option 2., also suggested at the link above, yields the error
Cannot convert type 'UnityEngineGameObject' to 'foo' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
Option 3. was suggested here and produces the error
NullReferenceException: Object reference not set to an instance of an object
This seems like a simple task, but I'm having a bit of trouble with this one. So, how can I determine the class/type of the object that my mouse is over?
Any help is greatly appreciated!
Answer by KoenigX3 · Jan 05, 2017 at 05:28 PM
The first line of code should work as intended. However, if the raycast returns without a gameobject, the 'objAtMouse' variable will be null, and it will produce errors.
First, you have to check whether 'objAtMouse' is an actual gameobject, then proceed with getting the right component. I assume that you are talking about 'foo' class as a script component on the gameobject (the raycasted gameobject will always have the type of 'GameObject', but the components on it will have other types).
if(objAtMouse != null)
{
// GameObject found, we can proceed
if(objAtMouse.GetComponent<Foo>() != null)
{
// The GameObject has a Foo-typed component on it
}
}
This part should be inserted after the raycasting line.
Thanks a bunch @$$anonymous$$oenigX3 for the helpful answer; that did the trick! :)