- Home /
Mouse Action on a GameObject member of a class
Hello there !
I'm new to Unity, and i am trying to find a way to make my item react to a mouse action. I saw in the doc that it was possible to do that, but i can't figure out how it works...
Here is an example :
public class Territory
{
private GameObject GOTerritory;
public bool MouseOverTerritory()
{
if(GOTerritory.collider. ??????????? ) // i think that i have to call something on the collider, but not sure
{
GOTerritory.renderer.material = GameObject.Find("MFSelected").renderer.material;
return true;
}
else
{
GOTerritory.renderer.material = GameObject.Find("MFNotSelected").renderer.material;
return false;
}
}
}
Here i try to change the material of my GameObject GOTerritory if my mouse is over it.
Am i looking in the good direction, or am i totally wrong about the way i should do it ?
PS : i don't assign this script to any gameobject. It is just a class that i use and i don't want it assignated to any gameobject. I just want to have my GameObjects as members of the class.
Thanks for your time, have a great day.
Answer by markedagain · Jul 11, 2013 at 03:48 PM
does the GOTerritory have its own script ?
if so what u can do is in the GOTerritory script u can make a bool IsMouseOver and then use monobehaviour's OnMouseEnter and OnMouseExit to turn it off and on.
after that in your territory script u can do
GOTerritory.transform.getComponent<GOTerritory>().isMouseOver
Thank you for the answer ! I did it an other way, but i will keep your answer in $$anonymous$$d and will do some test. I'm not very familiar with theses script things that you assign to objects. It seems to be pretty usefull.
Answer by Sephius · Jul 11, 2013 at 03:49 PM
Ok i figured out how it works. Just in case, i will put my code, if someone have the same question.
public bool MouseOverTerritory()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if(GOTerritory.collider.Raycast(ray,out hit,100))
{
GOTerritory.renderer.material = GameObject.Find("MFSelected").renderer.material;
return true;
}
else
{
GOTerritory.renderer.material = GameObject.Find("MFNotSelected").renderer.material;
return false;
}
}
Answer by cdrandin · Jul 11, 2013 at 03:47 PM
Try playing with the example provided by Unity. Just make a new script and just run what they have and see the relationship. http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnMouseOver.html