Glurth
1
I have some code to modify an object’s rotation transform in the update statement, but I’m not getting the results I expected …
This code snipped, run in Update(), works fine and rotates the object as expected:
Transform t = GetComponent<Transform> ();
Quaternion q = new Quaternion ();
q.SetLookRotation(lookat,new Vector3 (0, 1, 0));
t.rotation = q;
This code does NOT rotate the object. Why the heck not?
GetComponent<Transform> ().rotation.SetLookRotation(lookat,new Vector3 (0, 1, 0));
Note: lookat is a Vector3 variable setup earlier in the code: setup not relevant, I think, because I pass the same values to both versions of the code. (Debug.Log tests confirmed this)
I suspect I’m missing something simple and obvious here, but I’m still stumped.
I think your not-working examples are really compile errors, which the compiler should be flagging, but isn’t. The same sort of error as transform.position.x=5;. What compiler are you using?
rotation is a struct and transform.rotation is probably a set/get. That means you can change the entire thing using set, or play with a copy through get. I assume the compiler didn’t notice that SetLookRotation is changing itself, so didn’t flag anything. It just (incorrectly) said “here’s your rotation copy, have fun.”
Why doesn’t C# allow references to structs, like C++? I assume it would break garbage collection. Likewise, C# doesn’t have a const for member funcs, which might allow it to catch this easier.