- Home /
How can I make a game object follow an instantiated game object?
The main issue I am trying to resolve is that textures are stretching over a sphere a little poorly. I am going to have a plane represent the sphere, turn off the sphere's render and have the plane follow the sphere around without any collision.
Is there a way to make the plane act as a child and follow the instantiated game object around?
Appreciate the help. :)
Answer by robertbu · Jul 22, 2013 at 02:10 AM
If you want something like a child, just make it a child. That is set the Transform.parent of the plane to the transform of the sphere. I don't know how your game is constructed, but in the Start() for the sphere you can do something like:
GameObject go = GameObject.Find("Plane");
go.transform.parent = transform;
You could also do it the other way around. Have the sphere set its transform to a public variable on a script attached to the plane. The plane script might look like:
public Transform toFollow = null;
void Update() {
if (toFollow != null)
transform.position = toFollow.position;
}
The parent/child follows position, rotation, and scale. The second solution only follows the position, though it could be augmented to follow other properties.
Robert thank you for explaining how the parent works, it was a bit confusing for me. I have got kind of what I am looking for working based off your answer.
The plane(object type: plane) is not following the ball(sphere). Although the issue I am having is once the ball is destroyed and re-instantiated, the plane is misaligned. Any idea why that is the case when the plane's transform should be adhering to that of the ball/sphere?
void LaunchBall()
{
if (GameStarted == true)
{
if(attachedBall)
{
Rigidbody ballRigidbody = attachedBall.rigidbody;
ballRigidbody.position = transform.position + new Vector3(0,1f,0);
// Set the BallTexture's position to that of the AttachedBalls
var ballTextureTransform = ballTexture.transform;
ballTextureTransform.parent = attachedBall.transform;
if (Input.GetButtonDown("LaunchBall"))
{
ballRigidbody.is$$anonymous$$inematic = false;
ballRigidbody.AddForce(500f * Input.GetAxis ("Horizontal") + 100f,500f,0);
attachedBall = null;
}
}
}
}
If you are destroying the object that is the parent and then doing a new Instantiate(), the transform you set as the parent is gone and you must reset the parent to the new object you instantiated. When you say 'misaligned' do you mean the plane is rotate wrong? $$anonymous$$aking something a child does not change its location or rotation. In fact preserves the relative position and rotation between the two at the time the linkage was made. You likely have to reset the rotation around line 9 to the initial rotation of the plane just as you do for the position on line 8.