- Home /
Prefab set to destroy when outside of camera being destroyed on instantiation
Hi all! I've been having an issue with some code, where I'd like projectiles to vanish once they leave the screen. I've done this by checking if the sprite renderer is on screen each update and if not, destroy the object.
The problem with this is that it works when the player instantiates the projectile, it appears, travels and then vanishes when on screen. For some reason when I try to have one of the enemys instantiate the exact same projectile, the log for "is invisible" pops up immediatley and it's destroyed.
Any ideas or help are greatly appreciated, thank you!
public new Renderer renderer;
void Start()
{
renderer = GetComponentInChildren<Renderer>();
}
private void Update()
{
if (!renderer.isVisible)
{
Debug.Log("Object is not visible");
Destroy(gameObject);
}
}
Like I mentioned above they should be instanting the same way, on the player with a click and the enemy on a timer like so
//Player
void Shoot1()
{
//The Projectile fired will change based on player input
Instantiate(projectile1, new Vector3(transform.position.x, transform.position.y, transform.position.z), transform.rotation);
}
//Enemys
Count();
if (currentTime >= spawnTime)
{
Instantiate(projectile, new Vector3(transform.position.x, transform.position.y + spawnOffset,transform.position.z), transform.rotation);
currentTime = 0;
}
Update:I have since removed and added my player character prefab to the scene without making any adjustments to the code and now the projectiles are being destroyed upon instantiation from the player character too.
I can only assume it's a technical issue above my understanding of Unity
Answer by IceKapper85 · Apr 21, 2021 at 03:04 PM
Solved! Found the answer to my issue here: https://answers.unity.com/questions/41962/renderisvisible-returning-false-for-one-frame.html
Turns out that the renderer is set to invisible for one frame when created, now working as intended :D
Answer by gigos22 · Apr 21, 2021 at 02:39 PM
I don't get 2 things here:
Why aren't you just destroy the projectile once it reached it's target aka the enemy?
Why are you instantiating the projectile twice..? It should be instantiated just once, and then travel to it's target, and as mention above, destroyed on impact.
Hi Gigo22! The projectile is destroyed once it hits the enemy, as well as if it hits a wall, etc, I'd like it so that the player can only damage enemy's when they are on screen and vice versa.
Also it's only instantiating once, the second bit of code just takes from both the player script and the enemy script just to show that there aren't any significant differences that I can see to how they're instantiated
Thank you! I decided I prefer how it works without it, but it's all a fun learning expirience