how to assign different Gameobject to a single variable during run time using c#?
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).
Answer by Hellium · Jan 31, 2018 at 04:05 PM
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[i].OnClicked += OnTargetClicked;
}
}
private void OnTargetClicked( ClickTarget target )
{
CurrentTarget = target.gameObject;
}
}
Attach the following
ClickTarget
script to the objects that must be clicked. Don't forget to add aCollider
to each of them before
using UnityEngine;
using UnityEngine.EventSystems;
[RequireComponent(typeof(Collider))]
public class ClickTarget : MonoBehaviour, IPointerClickHandler
{
public System.Action<ClickTarget> OnClicked;
public void OnPointerClick( PointerEventData eventData )
{
if ( OnClicked != null )
OnClicked.Invoke( this );
}
}
Then, attach a Physics2DRaycaster
ins$$anonymous$$d of a PhysicsRaycaster
and attach Collider2D
components ins$$anonymous$$d of simple Colliders
Did the script work with the Physics2DRaycaster
and Collider2D
?