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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Destroy everything except player.

Discussion in 'Scripting' started by Kacpe2403, Mar 10, 2020.

  1. Kacpe2403

    Kacpe2403

    Joined:
    Mar 1, 2020
    Posts:
    8
    How can i destroy everything except player in this line?
    Destroy(other.gameObject);
     
  2. APSchmidtOfOld

    APSchmidtOfOld

    Joined:
    Aug 8, 2016
    Posts:
    4,473
    The line should do the job.
     
  3. Kacpe2403

    Kacpe2403

    Joined:
    Mar 1, 2020
    Posts:
    8
    But it's not player's script. Can I easily fix it? Like
    Destroy(other.gameObject, !GameObjectWithTag("Player"));
     
  4. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,386
    if (!other.gameObject.CompareTag("Player"))
    {
    Destroy(other.gameObject);
    }
     
  5. Kacpe2403

    Kacpe2403

    Joined:
    Mar 1, 2020
    Posts:
    8
  6. APSchmidtOfOld

    APSchmidtOfOld

    Joined:
    Aug 8, 2016
    Posts:
    4,473
  7. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    This is just written in notepad, so the syntax may be a little off...
    Code (CSharp):
    1. using System.Linq
    2.  
    3. GameObject.FindObjectsOfType(typeof(MonoBehaviour)).Select(obj => obj.tag != "Player").Foreach(obj => Destroy(obj));
    I'm not sure if you will get an error, as your deleting an object that you are also iterating through. But it should be fine as its not directly affecting the list.