My game object’s rotation equals (0,0,180),and My code is as follows
void start(){
var forward = transform.forward;
transform.forward = forward;
}
after code execution
game object’s rotation equals (0,0,0)
why?
And how to set tranform forward without reset Z coodinate?
Try putting some logging statements in there… I think your problem might be in different code:
void start(){
var forward = transform.forward;
Debug.Log("Forward before: ${transform.forward}");
transform.forward = forward;
Debug.Log("Forward after: ${transform.forward}");
}
using UnityEngine;
public class test : MonoBehaviour
{
void Start()
{
Debug.Log("before" + transform.eulerAngles.z);
transform.forward = transform.forward;
Debug.Log("after" + transform.eulerAngles.z);
}
}
Create a GameObject and set rotation z to 180 , and add this component to the gameobject,
it will log
before180
after0
Ohh you’re totally right. Ok I think I know what’s happening here. Instead of doing transform.forward = transform.forward try this:
transform.LookAt(transform.forward, transform.up);
basically when you set transform.forward to a value it calls Transform.LookAt with only one parameter. In that mode the “up” direction defaults to Vector3.up.
The reason it does this is because just specifying a place to look is not enough info to fully figure out the rotation. You also need to tell Unity which direction “up” should be.
Completely solved my problem, thank you