- Home /
How to make an object the child of another object through code?
i have 2 bullethole prefabs(plane + cutout texture) when i shoot them (instantiate) i want to make them the childen of the object it hits;
if i have a dynamic box for example i want the plane to move with the box.
How can i do that ?
using UnityEngine;
using System.Collections;
public class RayShooting : MonoBehaviour
{
public GameObject []bulletTex;
private GameObject currentTex;
public Transform crosshair;
public GameObject aimCamera;
public float rayRange=1000f;
void Update ()
{
Ray ray = camera.ViewportPointToRay(crosshair.position);
RaycastHit hit;
if(Input.GetButton("Fire1")&&(Physics.Raycast(ray, out hit))&&hit.collider.gameObject.CompareTag("Ground"))
{
currentTex=bulletTex[Random.Range(0,2)];
Instantiate(currentTex,hit.point,Quaternion.FromToRotation(Vector3.up,hit.normal));
currentTex.transform.parent=hit.collider.gameObject.transform.parent;//doesn`t work
}
}
}
Answer by ArkaneX · Sep 09, 2013 at 01:52 PM
You're trying to assign parent of the object you hit (and it's probably null) as a parent of your bullet hole. You have to change these lines:
Instantiate(currentTex,hit.point,Quaternion.FromToRotation(Vector3.up,hit.normal));
currentTex.transform.parent=hit.collider.gameObject.transform.parent;
to
var currentTexInstance = (GameObject)Instantiate(currentTex,hit.point,Quaternion.FromToRotation(Vector3.up,hit.normal));
currentTexInstance.transform.parent = hit.collider.gameObject.transform;
or just
var currentTexInstance = (GameObject)Instantiate(currentTex,hit.point,Quaternion.FromToRotation(Vector3.up,hit.normal));
currentTexInstance.transform.parent = hit.collider.transform;
EDIT: changed to assign parent of instance, not of the prefab itself.
ok i get an error setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.
my bullet textures are prefabs. is there a way around this?
You're righ - I missed this problem. The answer is now updated.
ok super but c# how`s that?
GameObject currentTexInstance = (GameObject)Instantiate(currentTex,hit.point,Quaternion.FromToRotation(Vector3.up,hit.normal));
currentTexInstance.transform.parent = hit.collider.transform;
??
and i`v got another error
Actor::update$$anonymous$$assFromShapes: Compute mesh inertia tensor failed for one of the actor's mesh shapes! Please change mesh geometry or supply a tensor manually!
when i shoot the dynamic box
That was C# syntax :) var is C# keyword as well, and denotes any type. You can check details on $$anonymous$$SDN page.
The second error you get is unrelated. I haven't encountered it, but if you google for update$$anonymous$$assFromShapes, you'll find a solution quickly.
thx man the error was caused by the interaction between the rigidbody of the box and the mesh colider of the bullethole
i fixed it by removing the mesh colliders of the bulletholes