After watching this episode, I was wondering why @Ben scrapped away the OnBecameInvisible method after introducing it, just due to the fact that the sprite component is actually in the Body child of the projectiles prefabs.
So, instead of adding a new shredder game object and a script, I just added a script to the Body childs of the two projectiles prefabs, which is as follows:
[code]
using UnityEngine;
using System.Collections;
public class DestroyProjectiles : MonoBehaviour {
void OnBecameInvisible(){
GameObject parentObj = transform.parent.gameObject;
Destroy(parentObj);
}
}[/code]
The other thing that I wanted to do programmatically was to spawn at the correct position the projectiles without the need to publicly expose the Gun child object in the script component.
Sadly, there’s no method that allows us to get a child game object by its name, so the only way that I found to do this was to use a foreach + if, as follows:
After a little bit of research, I found there’s indeed a method used to find child game objects in the hierarchy, the transform.Find([string]), so I modified the code scrapping away the foreach cycle:
using UnityEngine;
using System.Collections;
public class Shooter : MonoBehaviour {
public GameObject projectile, projectileParent;
private void FireGun(){
GameObject newProjectile = Instantiate(projectile, transform.Find("Gun").transform.position, Quaternion.identity) as GameObject;
newProjectile.transform.parent = projectileParent.transform;
}
}
Thoughts?