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){...}
-
if(fooAtMouse){…}foo fooAtMouse = objAtMouse as foo;
-
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!