- Home /
Unable to apply "transform" on gameobject from Raycast
I have 2 blocks, Block A is the player, Block B is part of a cube grid floor. I want to get the position of Block B from Block A. There are many Block Bs in the Scene.
I'm able to destroy the specific Block B the player is above (I'm using forward on the raycast this is correct), but can't get it's position. S o Ican zip around deleting the floor as I go, but can't get the position of any of these game objects :/
private float rayBlockCheckDistance = 10;
private void gridSnap()
{
RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, Vector3.forward, rayBlockCheckDistance);
GameObject gFloor = hits[0].transform.gameObject;
//Transform tFloor = gFloor.transform; //This Errors
//Vector3 position = new Vector3(tFloor.position); //So this Errors aswell
Destroy(gFloor); //But I can destroy the specific Block fine.
}
No errors are given for why I can't apply transform as thus get the position of the first object in the raycast array, the Editor just flashes "Compiler errors", but no errors are given in console or VS.
Both objects have box colliders/rigid bodies.
Other than what Larry-Dietz said, it also looks a bit concerning that you get hits[0] before checking that there actually are any hits. You should add a check if hits has a length greater than 0.
Answer by Larry-Dietz · Nov 27, 2019 at 11:03 PM
Looks like you are trying to set tFloor equal to an undeclared DirectFloor variable, Unless this is being initialized somewhere else. From looking at your code, I would first try changing that line to
Transform tFloor = gFloor.transform;
Then on the line below, change it to...
Vector3 position = tFloor.position;
The position variable of the transform is already a Vector3
One last thing, in your Destroy line, you can use Destroy(gFloor); since gFloor is already set to hits[0].transform.gameObject.
Hope this helps, -Larry
thanks for the response, "DirectFloor" was a typo by me, I've updated my code and the question, however I'm still getting "compiler error" on 'Transform tFloor = gFloor.transform'. Destroy works using gFloor so it clearly does contain the specific game object, but unable to access its transform.
I'll admit, you have me stumped. All game objects contain a transform as far as I know. And if your gFloor object is being removed from the scene when the destroy call runs, then you are right, gFloor must be populated.
When it errors, exactly what is the error message saying?
Your answer
Follow this Question
Related Questions
How do i get the transform of an object with raycasthit? 1 Answer
Linecast blocked by colliders not actually in the way? 0 Answers
C# Raycast goes straight into the air 2 Answers
NullReferenceException when using raycast 1 Answer
Maintain object position when using raycasting to multiple height 2 Answers