How i set image from Raycast hit target object?

I have 8 ui images. and i want set raycast hit object image to new gameobject image?

Default new image is white square.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class WorldManager : MonoBehaviour
{
    public GameObject decalsFolder;   

    public GameObject[] images = new GameObject[8];


    void Update()
        {


            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            {
                if (Input.GetMouseButtonDown(0))
                {

                    print(hit.point);
                
                    var nGo = new GameObject("temp");

                    GameObject go = Instantiate(nGo, hit.point, Quaternion.identity);
                    print("Created new Empty image");
                    go.transform.parent = decalsFolder.transform;
                    go.gameObject.AddComponent<Image>();
                    // go.gameObject.GetComponent<Image>().sprite = hit.collider.; 
                    go.gameObject.AddComponent<ItemDragHandler>(); // << This code is dragging code.
                    go.layer = 5;
                    // hit.collider.gameObject.SetActive(false);
                   go.transform.position = (Input.mousePosition);


                }
            }
        }
}

Hey!

I try this: go.gameObject.GetComponent().sprite = hit.collider.GetComponent().sprite;
but this go to error. I want change default sprite to hit.gameobject image.

but i have 8 images :confused: is so easy if i have 2 images and changes.

Does the thing Raycast where it hits? check: Aah player hits image[2] and create empty gameobject with this [image[2] sprite.

Is so hard to me…

You can use 3d methods for 2d game. Create new gameobject named “imgObje”. We will use this name in our script. Add SpriteRenderer, BoxCollider, and my script whose name is “ChangeImage” as a component.

Use the scrpit below

     public List<Sprite> imgList = new List<Sprite>();
     public Camera cam;
     private int currentIndex = 0;
     RaycastHit hit;
     private SpriteRenderer renderer;
     private void Awake()
     {
          renderer = GetComponent<SpriteRenderer>();
     }

     void Update()
    {
          if (Input.GetMouseButtonDown(0))
          {
               Ray ray = cam.ScreenPointToRay(Input.mousePosition);
               if (Physics.Raycast(ray,out hit ))
               {
                    if (hit.collider.name=="imgObje")
                    {
                         currentIndex++;
                         if (currentIndex>=imgList.Count)
                         {
                              currentIndex = 0;
                         }
                         renderer.sprite = imgList[currentIndex];
                    }
               }

          }
        
    }

Drag the sprites in assets folder to imgList variable134850-img2.png