Reputation: 25
I have a problem with my puzzle mechanic that I just can't seem to be able to wrap my head around. I have a pylon that shoots beams into end points and these end points will then power up other things.
Each puzzle has multiple end points but no puzzle has the same amount, so I figured the best way would be to use a public list that I then make the same size as all the end points in the specific puzzle. If the puzzle has 3 end points, I'll assign 3 to the list and then drag and drop the end points into the slots in the inspector.
My problem comes at this point, because I have no idea how to now access the stuff inside the game objects in the list, such as to check their transform if the raycasting of the beam will hit them, or access their variables.
The following code doesn't work as "if (hit.transform == endPoints.transform)
" is not correct but I've tried everything I can think of and spent too much time googling this problem. I just don't know how to proceed.
public List<GameObject> endPoints;
void Raycaster()
{
RaycastHit hit;
Debug.DrawRay(transform.position, transform.forward * rayDistance, Color.red);
if (Physics.Raycast (transform.position, transform.forward * rayDistance, out hit)) // Check the raycast
{
if (hit.transform == endPoints.transform) // Does it hit the specified object?
{
Debug.Log ("It hit the thing");
}
else
{
Debug.Log ("It did not hit the thing");
}
}
}
Upvotes: 1
Views: 61
Reputation:
You need to check for each element in endPoints. So you need to use a for
loop, for example. You can do it like this:
public List<GameObject> endPoints;
void Raycaster()
{
RaycastHit hit;
Debug.DrawRay(transform.position, transform.forward * rayDistance, Color.red);
if (Physics.Raycast (transform.position, transform.forward * rayDistance, out hit)) // Check the raycast
{
for (var i = 0; i < endPoints.Count; i++) { // Do this for each element in endPoints
if (hit.transform == endPoints[i].transform) // Does it hit the specified object?
{
Debug.Log ("It hit the thing number " + i);
}
else
{
Debug.Log ("It did not hit the thing");
}
}
}
}
On a side note, I would not do that: hit.transform == endPoints[i].transform
Since a transform in Unity also holds information regarding the scale and rotation, I would only perform this check for the position: hit.transform.position == endPoints[i].transform.position
Upvotes: 1