- Home /
Instantiate prefab to the parent
Hello, I would want to instantiate a prefab in a parent with a raycast, but the problem, it is that I do not do, here is my code, please help me.
public Ray ray; public RaycastHit hit; public GameObject BulletHole; public float FireRate = 0.5F; public float DistanceFired = 250F; public static int Ammo = 30; public int MaxAmmo = 30; public int force = 200; public HandPunching _HandPunching; private float nextFire; void Fire () { //Var Vector3 fwd = transform.TransformDirection (Vector3.forward); var hitRotation = Quaternion.FromToRotation (Vector3.up, hit.normal); _HandPunching.LeftPunching(); Ammo -= 1; if (Physics.Raycast (transform.position, fwd, out hit, DistanceFired)) { GameObject go = Instantiate (BulletHole, hit.point + (hit.normal * 0.01F) , hitRotation) as GameObject; Destroy (go, 300); Debug.DrawLine (transform.position, hit.point, Color.blue); print ("" + hit.distance + " meters"); if (hit.rigidbody) hit.rigidbody.AddForceAtPosition(force * fwd, hit.point); }
Answer by iaroslav-titov · Feb 05, 2016 at 04:42 PM
Try instantiantiating it first, and only then change the position/rotation/anything. Worked for me
GameObject instance = Instantiate(Resources.Load("Prefabs/NAME", typeof(GameObject))) as GameObject;
instance.name = "name";
instance.transform.parent = transform; // this binds it to the parent object
instance.transform.position = yourPosition;
etc.