transform.rotation has a different value in different events
Hi, I'm trying to make a cannon fire a ball. However, transform.rotation in the "Aim" event is correct, while transform.rotation in the "Fire" event is the empty quaternion. The only difference between the "Aim" and "Fire" events is that "Aim" is a Value / Axis event and "Fire" is a button event.
My code:
private float angleRate; // Degrees per frame.
// Update is called once per frame
void Update()
{
transform.Rotate(0, 0, angleRate);
}
// Rotate the cannon.
public void Aim(InputAction.CallbackContext context)
{
Vector3 axis = new Vector3(-1, -1, -1);
float angle = -1;
// Aim the cannon.
if (context.started)
{
angleRate = context.ReadValue<float>();
transform.rotation.ToAngleAxis(out angle, out axis);
Debug.Log("Aim! " + angle + " @ " + axis + " {" + transform.rotation + "}");
} else if (context.canceled)
{
angleRate = 0f;
transform.rotation.ToAngleAxis(out angle, out axis);
Debug.Log("Stop! " + angle + " @ " + axis + " {" + transform.rotation + "}");
}
}
public void Fire(InputAction.CallbackContext context)
{
Vector3 axis = new Vector3(-1, -1, -1);
float angle = -1;
transform.rotation.ToAngleAxis(out angle, out axis);
Debug.Log("Fire! " + angle + " @ " + axis + " {" + transform.rotation + "}");`
}
Sample output:
Aim! 0 @ (1.0, 0.0, 0.0) {(0.0, 0.0, 0.0, 1.0)}
Stop! 24.89999 @ (0.0, 0.0, -1.0) {(0.0, 0.0, -0.2, 1.0)}
Fire! 0 @ (1.0, 0.0, 0.0) {(0.0, 0.0, 0.0, 1.0)}
(the output for "Fire" does not change for context.performed and context.canceled".)
Everything I've tried hasn't worked; any help is appreciated. Thanks!
Answer by Bunny83 · Oct 03, 2021 at 10:14 AM
Are you sure that your 3 logs actually come from the same gameobject? When you debug and you get such different results, chances are high the script is attached to more than one object and you may have wired things the wrong way.
Try adding a context object to your Debug.Log statements. By passing a UnityEngine.Object derived type as second parameter you can click on the log message in the console and Unity will highlight / ping that object in your project / hierarchy so you know exactly which object the message belongs to.
So try
Debug.Log("Fire! " + angle + " @ " + axis.ToString("F5") + " {" + transform.rotation.ToString("F5") + "}", gameObject);
Click on the log message to see which gameobject this came from. Make sure all 3 messages came from the same object. In addition you could also print the object's name or whatever necessary to identify the object.
You're right, they were different game objects. I'm very confused about how I set it up that way, but I linked the prefab's events to the prefab and created a new instance in the scene. That seems to have fixed it.
Thanks!