- Home /
Problem Solved
Instantiate with parent not working?
I'm not sure what happened to cause this, but for some reason the instantiated object I'm creating is not being instantiated with a parent. Basically, I'm making a 3d game somewhat along the lines of the classic game Asteroids. In the game there is a player ship as well as enemy ships which fire at the player. When the player clicks it instantiates a torpedo with the following code:
if (Input.GetButtonUp("Fire1"))
{
Instantiate(torpedo, transform.position, transform.rotation, transform);
}
In order to prevent the torpedo from just exploding on the player's ship I had to make sure it was instantiated as a child of the player and then in it's onTriggerEnter check if the collider is that of the parent(playership). This works fine for the player, however, when the enemy ships instantiate torpedos of their own with the same call to instantiate, the instantiated torpedos are not instantiated with the enemy ship as their parent, causing the torpedo to explode on the enemy ship. I have checked this with a debug log. Oddly enough, it seems that the torpedo is being set as a child of the enemy ship in the hierarchy, however the debug check(along with the if statement) I've set up refuses to acknowledge that.
Enemy ship instantiate call(checks if raycast hits player before firing):
void attack()
{
RaycastHit hit;
if (Physics.Raycast (transform.position, transform.forward, out hit))
{
if(hit.collider.gameObject.tag == "Player")
{
Instantiate(torpedo, transform.position, transform.rotation, transform);
StartCoroutine(ChargeTorpedo());
}
}
}
and the torpedo's script:
using UnityEngine;
using System.Collections;
public class TorpedoManager : MonoBehaviour {
Rigidbody rb;
Collider parentColl;
public GameObject explosion;
float speed = 100f;
// Use this for initialization
void Start ()
{
Debug.Log(transform.parent.gameObject.name);
rb = GetComponent<Rigidbody>();
parentColl = transform.parent.GetComponent<Collider>();
rb.velocity = GetComponentInParent<Rigidbody>().velocity;
StartCoroutine(Lifetime());
}
void FixedUpdate()
{
Move();
}
void Move()
{
rb.AddRelativeForce(Vector3.forward * speed);
}
void OnTriggerEnter(Collider other)
{
if (other != parentColl)
{
Instantiate(explosion, transform.position, transform.rotation);
Destroy(this.gameObject);
}
}
IEnumerator Lifetime()
{
yield return new WaitForSeconds(3f);
Instantiate(explosion, transform.position, transform.rotation);
Destroy(this.gameObject);
}
}
Can anyone help me figure out what's going on here?
I've changed the start function on the torpedo to awake and it seems to have fixed it. I guess the ontriggerenter was managing to get called before start had a chance to set parentcoll