- Home /
SInce when?!?!? (Raycast issue)
okay, I don't use raycast a lot, but I've seen a pretty good deal of scripts that use a raycast and get info back from it. I copy/pasted the raycast part of this script and just changed the variable names. here's what I have
var target : Transform;
function Update () {
if (!target){
transform.Rotate(0,50,0); // raycast
var hit : RaycastHit[]; hit = Physics.RaycastAll(transform.position, transform.forward, 100.0); if (hit.collider.gameObject.tag == "PBP"){
//target = hit.collider.gameObject;
}}}
I just want to assign the hit object as my target, but I get an error message : Assets/Scripts/BuildPoint.js(12,9): BCE0019: 'collider' is not a member of 'UnityEngine.RaycastHit[]'.
Since when is collider not a member of raycast hit? The api clearly states that it is, and I've seen loads of scripts use it. What am I doing wrong?
Answer by GesterX · Apr 30, 2011 at 11:55 PM
Remove the [] after RaycastHit.
By putting a [] after it you are getting an array of everything that was hit (I think - someone feel free to correct me if I'm wrong)
You are then trying to do array.collider which does not exist since hit refers to an array of hits.
EDIT: Your code is slightly off. Try this:
var hit : RaycastHit;
if (Physics.Raycast (transform.position, -Vector3.up, hit, 100.0)) {
if (hit.collider.gameObject.tag == "PBP"){
//do your stuff
}
}
good thought, but now it says :
Assets/Scripts/BuildPoint.js(11,27): BCE0022: Cannot convert 'UnityEngine.RaycastHit[]' to 'UnityEngine.RaycastHit'.
Also, I would think that its telling me that the raycast isnt returning an object with a collider, but then it would just stop the test of the game. ins$$anonymous$$d, it wont even compile it, so that tells me it is indeed a code error
checkout my edit of my answer. It should work for you. Check out the script reference for more info http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html
no worries. You can pretty much re-use this for 90% of raycast situations :-)
Answer by Joshua · May 01, 2011 at 05:00 AM
The problem is not that use you RaycastAll which returns RaycastHit[] instead of Raycast which returns RaycastHit. The problem is that you don't use the information RaycastHit[] returns correctly. Instead of checking wether it is a collider with a certain tag you must check if it contains a collider with that tag. So simply loop through it using
for(i=0;i<hit.length;i++) {
if (hit[i].collider.gameObject.tag == "PBD"){
target = hit[i].collider.gameObject;
return;
}
}
Your answer
Follow this Question
Related Questions
Raycasting ignoring small sized object 1 Answer
Raycasting Collider Problem 0 Answers
How can I let the ray to the edge of the capsule? 1 Answer
Raycast exit point of collider 0 Answers
(C#) Collider to collider2d 0 Answers