- Home /
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);
}
}
}
}
Answer by JoniBerg · Mar 16, 2019 at 01:52 PM
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 :/ 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...
Answer by badadam · Mar 16, 2019 at 05:14 PM
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 variable
I own these pictures and would like to copy them to a new object When i click pic new object get pic graphics. How this works?
$$anonymous$$y inventory : [1]: http://imgur.com/a/8rl7pow
Right now new objects get default pic white quare
And second problem is raycast. Now i can raycast every where in scene.
How i limited raycasting hits only in picture inventory? @badadam
Your answer
Follow this Question
Related Questions
Raycast from 2D canvas object to world space 1 Answer
Ui scaling 1 Answer
How to make thumbnails from GameObjects? 3 Answers