i want instantiate a Ui image where user click with mouse on canvas. like clicking on canvas generate a image on mouse position click
I am not entirely sure this script can be added to the Canvas directly, but I have done something similar with a Panel before.
private void Update()
{
if (WasClicked())
{
AddImageAt(Input.mousePosition);
}
}
private bool WasClicked()
{
var pointer = new PointerEventData(EventSystem.current);
pointer.position = Input.mousePosition;
var _hitObjects = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointer, _hitObjects);
if (_hitObjects.Count > 0) return false;
// To not allow user to click through other UI elements, use...
return _hitObjects.First().gameObject == gameObject;
// To allow user to click through other UI elements, use...
// return _hitObjects.Any().gameObject == gameObject;
}
private void AddImageAt(Vector3 position)
{
var gameObject= new GameObject();
gameObject.AddComponent<Image>();
gameObject.transform.position = position;
gameObject.transform.SetParent(transform, false);
}