- Home /
Can't find a clone object with RayCast? [Solved]
I have a simple code that returns bool. And it works perfect with original prefab, but it fails to execute this part with a clone of the same pref if (hit.collider.gameObject == thisObject)
Here is the full part of code:
private bool HitPlayerCollider(GameObject thisObject)
{
bool hitResult = false;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 3000))
{
if (hit.collider.gameObject == thisObject)
{
hitResult = true;
}
else
{
hitResult = false;
}
}
return hitResult;
}
Script is attached to the Player.
Answer by ASPePeX · Mar 09, 2017 at 10:15 AM
Different instances of the same prefab are not the same gameobject!
Assigning a tag to your prefab and try this:
if (hit.collider.gameObject.tag == thisObject.tag)
{
hitResult = true;
}
else
{
hitResult = false;
}
Edit: This assumes that the main gameobject for the prefab also has the collider attached. If not you have to set the tag for the main gemeobject of the prefab as well as the gameobject that holds the collider.
Still can't hit an Clone object if (hit.collider.gameObject.tag == thisObject.tag)
Here is the start part of code to select the object maybe there is an issue;
if (Input.Get$$anonymous$$ouseButton(0))
{
if (HitPlayerCollider(gameObject))
{
Debug.Log(HitPlayerCollider(gameObject));
PlayerProjector.SetActive(true);
Controller.enabled = true;
}
else
{
PlayerProjector.SetActive(false);
Controller.enabled = false;
}
}
If check the thisObject.name
and gameObject.name
with Debug.Log
it gives the right name so it places the right object in to a Variable to compare, but I do not understand why it returns false if objects are equal.
Answer by Harardin · Mar 09, 2017 at 11:23 AM
It was my mistake a had a bigger TriggerCollider in the scene and it brings the issue.
Solved thenks to this answer by @Okido http://answers.unity3d.com/questions/279514/raycast-ignore-trigger-colliders.html