Set parent of an object when they collide?
I am trying to make an object collide with another object and then set it's parent to it so when they move they move as one and I want the new child to have the position it did when it collided with it's new parent. I have the child set it's position to where it collided with the other object but I can't figure out how to parent it so when the applied force of the child moves the parent they both move. my script: using UnityEngine; using System.Collections;
public class HarpoonSharp : MonoBehaviour {
public float power = 3000;
private Rigidbody rb;
void Awake () {
transform.Rotate(Vector3.right, 90);
}
void Start () {
rb = GetComponent<Rigidbody>();
rb.AddForce(transform.up * power);
}
void Update () {
}
void OnCollisionEnter(Collision collision) {
if (collision.collider.tag == "Stabable") {
ContactPoint contact = collision.contacts[0];
Vector3 pos = contact.point;
transform.position = pos;
transform.rotation = transform.rotation;
}
}
}
Answer by rockyourteeth · Oct 13, 2015 at 03:08 AM
Use this:
gameObject.GetComponent<Transform>().SetParent(collision.collider.gameObject);
(http://docs.unity3d.com/ScriptReference/Transform.SetParent.html)
And then you probably also want to turn off its physics component so it just moves with its parent...
rb.isKinematic = false;
(http://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html)
Answer by veome · Jun 10, 2016 at 04:34 PM
Try this:
projectle.transform.SetParent(Collided.gameObject.transform);
just replace 'projectile' with the name of your child object.