Hi all,
I’m having trouble manipulating a child object’s rotation from its parent object’s script. I found a few posts regarding this issue but I still don’t seem to be able to get it working correctly. I’ve writing the code in several ways but none seem to be working; here is my latest iteration:
Quaternion rotatex;
void Awake()
{
rotatex = GetComponentInChildren<Transform>().rotation;
rotatex.x = 30;
}
This is part of a script attached to a parent object “Player” which has a child object with a transform and sprite image. I’m trying to change the rotation of that sprite without effecting the rotation of the parent object.
Thanks!
Probably better to provide an example using Euler Angles:
Vector3 rotatex;
void Awake()
{
rotatex = GetComponentInChildren<Transform>().rotation.eulerAngles;
rotatex = new Vector3 (30, 0, 0);
}
Vector3 is not a reference type so you need to assign a new value to rotatex and then assign the child’s rotation to rotatex.
Edit: or you can skip rotatex and just do
GetComponentInChildren<Transform>().rotation.eulerAngles=new Vector3(0f,30f,0f);
or whatever.
When I use the line of code you provided I get an error CS1612:
“Cannot modify the return value of ‘Transform.rotation’ because it is not a variable”
So in that case I then tried to set a new variable for “GetComponentInChildren.rotation.eulerAngles”, then setting that new variable equal to the value of rotatex, which I had already set to “30f, 0f, 0f”. This did not work:
Vector3 rotatex;
Vector3 rot;
void Awake()
{
rotatex = new Vector3(30f, 0f, 0f);
rot = GetComponentInChildren<Transform>().rotation.eulerAngles;
rot = rotatex;
}
I’m not sure what the issue is when you say “Vector3 is not a reference type” so I tried setting the variable “rot” as a Transform. This also returns the same CS1612 error:
Vector3 rotatex;
Transform rot;
void Awake()
{
rotatex = new Vector3(30f, 0f, 0f);
rot = GetComponentInChildren<Transform>();
rot.rotation.eulerAngles = rotatex;
}
Oh, try just GetComponentInChildren<Transform>().eulerAngles
instead of GetComponentInChildren<Transform>().rotation.eulerAngles
Thanks! It’s working now. I’m kind of curious to know why the values in the inspector aren’t changing, though.
Wait, no, false celebration. The parent is rotating, not the child. That’s why I didn’t see it in the inspector. Why is the parent rotating?