1
\$\begingroup\$

So I'm working on a simple drag-n-drop based trading card game for my own amusement.

There is a card inspector included.

What I want to achieve is to change values in the inspector (which has its own Inspector.cs, so I would change the variables in it) based on which card I hover over with my mouse.

Each card has its own Card.cs attached from which I want to read the values of the current card.

If I try to do this from within the Inspector.cs by something like this: Name.text = gameobject.GetComponent<Card>().Name;, then obviously it won't work, because using gameobject in the current context is not valid.

So solution No1 would be to properly reference the gameobject over which the mouse is, which I don't know how to do.

When I try to do the same from within Card.cs, I cannot use an event trigger OnPointerEnter and run the code through that, because I have to have a reference to the gameobject that contains that function. ( And I cannot do that in a prefab, only in gameobject already existing in the level.)

So could anyone tell me how I could achieve what I want, please?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Physics.Raycast will help you to get the gameobject using mousePosition and ScreenPointToRay

 using UnityEngine;
 using System.Collections;

 public class Example : MonoBehaviour
 {
     Ray ray;
     RaycastHit hit;

     void Update()
     {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(ray, out hit))
         {
             print (hit.collider.name);
         }
     }
 }
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Thanks, though eventually I could solve the problem implementing IPointerEnterHandler and using the OnPointerEnter() method. That worked, unlike OnMouseEnter() \$\endgroup\$
    – spartai
    May 27, 2016 at 22:11
  • \$\begingroup\$ I didn't test your answer, because I had already managed to make it work by the time you posted the answer. I'll believe that it works though and accept it anyway \$\endgroup\$
    – spartai
    Jun 29, 2016 at 22:12
  • \$\begingroup\$ The above solution didnt work for me but implementing IPointerEnterHandler did \$\endgroup\$
    – dasLort
    Dec 17, 2020 at 18:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .