- Home /
Other
need help on raycast
hi, i have a script which has to detect the gameobject from screen which the mouse clicks and display the name of it. am trying to figure out where am making the mistake. need help on this.
using UnityEngine;
using System.Collections;
public class eventManager_2 : MonoBehaviour {
public GameObject cardPrefab;
// Use this for initialization
void Start () {
cardCreation ();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit))
{
print (hit.collider.name);
}
}
}
void cardCreation()
{
float heightOffset = (cardPrefab.transform.position.y) + 1.2f;
for(int i = 1; i < 10; i++)
{
//for(int j = i; j > i; j++)
//{
GameObject cardsTemp = (GameObject)Instantiate(cardPrefab);
//cardsTemp.transform.position = new Vector3(-8.0f ,(transform.position.y - 3.0f + i),0);
cardsTemp.transform.position = new Vector3(-8.0f , (i * heightOffset) - 4.8f ,0);
//}
}
}
}
Could you give some more information on what's going wrong? Is it not working at all, or is it just buggy?
Do you have right colliders on your gameObjects? For example it must have BoxCollider, but not BoxCollider2D.
Answer by Utamaru · Mar 19, 2015 at 03:14 PM
I would recommend you to use new unity EventSystems. For example, if you want to catch clicks on your gameObjects, just implement IPointerClickHandler interface in script, attached to your gameObject. And then, when click on your object happens, OnPointerClick message will be called. You also need to add PhysicsRaycaster component to your main camera. Don't forget to do that.
Example code from my project:
public class FindableObject : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick (PointerEventData eventData)
{
Debug.Log ("OnPointerClick " + gameObject.name);
}
}
actually its my fault, i didn't scale the collider according to the size of the prefab. the script is fine its working.
thanks Utamaru for showing ur response.
Follow this Question
Related Questions
Mouse controlled Laserpointer 1 Answer
Mouse clicking on an object (Raycast.hit) for another object to connect to it? 0 Answers
in rewarded ad which code means user closed the ad by itself 2 Answers
Mouse button not detected with "Fire1" and Colliders 2 Answers
After upgrade to unity 2019.3, my mouse/ click drag object placement is all over the place 0 Answers