Actually what i want is , on clicking over Gameobject it should be stored in a variable for accessing , but if i click some other Gameobject then i should again stored in the same object(i m doing this because i have 24 Gameobjects in a single scene and all of them need to perform action on mouse click).
Supposing you are working with 3D objects
-
Add an EventSystem in your scene (GameObject > UI > EventSystem)
-
Attach a Physics Raycaster to the event system
-
Create an empty with the following
ClickTargetsManager
script:using UnityEngine;
public class ClickTargetsManager : MonoBehaviour
{
public GameObject CurrentTarget;private void Start() { ClickTarget[] targets = FindObjectsOfType<ClickTarget>(); for ( int i = 0 ; i < targets.Length ; i++ ) { targets*.OnClicked += OnTargetClicked;*
}
}
private void OnTargetClicked( ClickTarget target )
{
CurrentTarget = target.gameObject;
}
}
4. Attach the following ClickTarget
script to the objects that must be clicked. Don’t forget to add a Collider
to each of them before
using UnityEngine;
using UnityEngine.EventSystems;
[RequireComponent(typeof(Collider))]
public class ClickTarget : MonoBehaviour, IPointerClickHandler
{
public System.Action OnClicked;
public void OnPointerClick( PointerEventData eventData )
{
if ( OnClicked != null )
OnClicked.Invoke( this );
}
}