- Home /
Question by
JoniBerg · Mar 20, 2019 at 02:15 PM ·
uiraycastmouseposition
What is error on Raycasting?
Why i create new gameobject without raycast hit?
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("Luodaan uusi image");
go.gameObject.tag = "Decal";
go.transform.parent = decalsFolder.transform;
go.gameObject.AddComponent<Image>();
go.gameObject.AddComponent<BoxCollider2D>();
go.gameObject.GetComponent<BoxCollider2D>().isTrigger = true;
go.gameObject.AddComponent<Rigidbody2D>();
go.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0;
go.gameObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
// go.gameObject.GetComponent<Rigidbody>().isKinematic = true;
// go.gameObject.GetComponent<Image>().sprite = hit.collider.;
go.gameObject.AddComponent<ItemDragHandler>();
go.layer = 5;
// hit.collider.gameObject.SetActive(false);
go.transform.position = (Input.mousePosition);
}
}
}
This photo raycast hit point is empty: https://imgur.com/a/8cTWMrh
Comment
You are creating a gameobject without a raycast hit because you are not checking if the raycast hit anything. You should add an if statement if (hit.collider != null)
I fix code to:
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
print(hit.collider.name);
var nGo = new GameObject("temp");
GameObject go = Instantiate(nGo, hit.point, Quaternion.identity);
print("Created new image");
go.transform.parent = decalsFolder.transform;
go.gameObject.AddComponent<Image>();
// go.gameObject.GetComponent<Image>().sprite = hit.collider.;
go.gameObject.AddComponent<ItemDragHandler>();
go.layer = 5;
// hit.collider.gameObject.SetActive(false);
go.transform.position = (Input.mousePosition);
}
Now i see buttons effect if is pressed but why new image no created? :( Is so simple bug. @Ymrasu
Your answer
![](https://koobas.hobune.stream/wayback/20220612193943im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
OnPointerEnter and OnPointerExit not being triggered 0 Answers
Drag object and position(snap) on another similar one using Raycasting? 0 Answers
What's an easy way to align a UI element with a Raycast? 0 Answers
Help, Use event system IPointerClickHandler 1 Answer
Instantiated an Prefab on a Spherical Object at mouse cursor position 3 Answers