- Home /
Error getting the transform of a child object.
I am trying to rotate a child object by its transform, but instead if the child rotating the parent does.
GameObject lObject;
Transform lTransform;
void Start ()
{
lObject = new GameObject("lObject");;
lObject.transform.SetParent(transform);
lTransform = gameObject.GetComponentInChildren<Transform>();
}
void Update ()
{
lTransform.Rotate(Input.GetAxisRaw("Mouse Y"),0,0);
}
Answer by Baste · Feb 20, 2015 at 02:41 PM
GetComponentInChildren starts looking at this object, and then starts looking at the children. GetComponentInParent does the same thing.
This means that GetComponentInChildren will always return the transform of this object.
If you only have one child, you can do:
lTransform = transform.GetChild(0);
It's for my player character, who has a camera, weapon, etc. All attached as children. This is how I ended up solving my problem.
lObject = new GameObject("lObject");
lObject.transform.SetParent(transform);
lTransform = lObject.GetComponent<Transform>();
It is just as simple, but I am sad GetComponentInChildren didnt work the way i needed.
Your answer
Follow this Question
Related Questions
movement to certain child object 0 Answers
2D platformer firing left and right, help! 1 Answer
Rotating a transform using it's child 2 Answers
Rotating a bone via scripts 1 Answer
Why do we access children through an object's transform? 2 Answers