- Home /
Changing transform.position does not update the objects position
I'm creating a drone for my player that will launch from their back.
When activating the drone, the player's camera is disabled and the drone's camera is enabled.
The drone's camera clips into the players back which is unacceptable. To stop this happening I created a method that will 'launch' the drone from above their head, with a Raycast checking above them incase of an obstacle.
Here is the launch code from the Drone script:
void launch(){
Vector3 launchPos;
RaycastHit hit;
if(Physics.Raycast(transform.position, Vector3.up, out hit, maxLaunchHeight)){
launchPos = hit.point;
launchPos.y -= 0.25f;
} else {
launchPos = transform.position;
launchPos.y += maxLaunchHeight;
}
Debug.Log("before: "+transform.position);
transform.position = launchPos;
Debug.Log("after: "+ transform.position);
}
The problem I am having is that updating transform.position does not actually change the position of the object; it is not raised above their head upon activation.
I can see through debugging that transform.position.y is being changed to the desired value but it doesn't appear it is actually being applied to the object.
Strangely, I can change transform.position in the Update method - to help debug I added a bool that if true would set the position to some vector and when setting it to true mid-game it moves the drone to that vector without issue.
Any ideas as to why this might be happening?
If there is not enough info please let me know and I'll be happy to post more code / try and explain it better.
It seems to me that this code is not wrong per se, I think transform.position gets overwritten in your Update() method. Check the flow of your Update() method
Thank you for the reply. I took your advice and sequentially commented out the methods affecting transform.position until it became clear it was the CharacterController overwriting my changes.
No worries, glad you've found the solution! Going through your code from start to finish, line by line is called dry-running. Often it's the only way to catch an error :)
Answer by alexd991 · Mar 17 at 11:45 AM
I have solved the problem.
I am using a CharacterController to move the drone around and it appears that CC overwrites transform.position. This means it was set for one frame only when launching and then CC took it back to its previous position.
To solve this I have disabled CC until after I have set transform.position and it now works as expected. Hope this helps anyone with a similar issue.
Your answer
Follow this Question
Related Questions
ping pong on x axis, unable to touch end of plane, 1 Answer
Need help updating camera position to go above the player 2 Answers
AI movement using Character Controller, turning problem 1 Answer
How do I get the transforms of all the objects in my scene ? 2 Answers
Check if there is a object in front of you and equal your velocity to that objects 0 Answers