Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

C# How to destroy instantiated objects after a certain distance?

Discussion in 'Scripting' started by RayDawg, Feb 3, 2015.

  1. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    Currently, I have a top down view of my player character with the main camera following said character. I can instantiate multiple shots from my character, but I don't know how to destroy them after a certain distance. Can someone point me in the right direction? I don't want to use box collider attached to the main camera trick because if the camera moves, so will the box collider and the shots will never hit the collider/exit the collider trigger.
     
  2. gamer_boy_81

    gamer_boy_81

    Joined:
    Jun 13, 2014
    Posts:
    169
    Code (CSharp):
    1. Vector3 v_dir = projectile.transform.position - character.transform.position;
    2. if (v_dir.sqrMagnitude > maxDistance * maxDistance) {
    3.    Destroy(projectile);
    4. }
    You might not want to do it every frame, so maybe
    execute this every few frames
     
  3. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    This code was inserted into my projectile's script and it didn't do anything. Same thing for my firing script. Could you explain what is going on? Why maxDistance * maxDistance?
     
  4. Zaladur

    Zaladur

    Joined:
    Oct 20, 2012
    Posts:
    392
    You need to fill in what the projectile is and what the character is for this code to work. Generally you can't just copy code into your project from the forum and have it magically work.

    maxDistance * maxDistance is used because it is compared to v_dir.sqrMagnitude, or the Square Magnitute of the vector. Square root operations are expensive so some people avoid it by comparing the squares of values.
     
  5. gamer_boy_81

    gamer_boy_81

    Joined:
    Jun 13, 2014
    Posts:
    169
    Yes, like Zaladur says , square root operations are expensive, so this is why we use squared times
    directly.

    You can give a value to maxDistance - its the distance beyond which you want the projectile
    to go boom.