- Home /
Unity Raycast2D ignored instantiated Prefab object
I'm currently making a small game for a university assignment. It's a simple 2D game where you shoot birds using the mouse.
I did collission detection by hand at first (check for x/y boundaries) but now I wanna use a collider.
So I added a CircleCollider2D to my objects and I perform the Raycast like so
Vector3 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D[] hits = Physics2D.RaycastAll (mousePosition, Vector3.forward, Mathf.Infinity);
Debug.Log (hits.Length);
Now when I add my prefabs manually into my scene it works as expected. The log outputs 1, or even 2 if I have multiple birds on top of each other.
But my game instantiated a lot of birds randomly and they are not detected when performing the raycast. I already checked, they definitely have colliders.
The instantiation code looks like the following:
Bird bird = Instantiate (birdPrefab, birdPosition, Quaternion.identity) as Bird;
I googled around for 2 hours now, but nothing could actually solve my problem.
I don't know if this is important, but the collision detection does not happen within the bird object's attached script.
I'm really cofused because it works with manually put objects, but not with instantiated ones. Has anybody experienced this before?
The mouse position is on (x, y, -10) and the birds are on (x, y, 0) and both the manually placed ones and the instantiated ones are direct children of the scene.
I'm unable to reproduce your issue. Your code is working fine in my project. Double check that the prefabs are instantiated with 2D colliders and not 3D colliders.
Your answer
Follow this Question
Related Questions
Raycast causes game to crash when shooting up 1 Answer
how to move an object clone to mouse position, i dont understand ? 1 Answer
Cutting a Sprite 0 Answers
how to prevent an gameobject of instantiating if theres an collider where it is supposed to collide 1 Answer
What would be a good way to not have objects spawn inside one another? 2 Answers