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

Am I doing this right?..

Discussion in 'Scripting' started by Draconic, Sep 13, 2014.

  1. Draconic

    Draconic

    Joined:
    Oct 12, 2013
    Posts:
    82
    My project is rather large now, and there are many types of objects that need to be aware of each other. I have been using a class called World, which I use in each of the levels. Every other class has a reference to the World class. In the World class, I have arrays/lists of each type of object, which update at the Start () and at Update (). By doing this, for example, I can use a for loop on one of the World classes arrays to have an object in the scene detect if it is a specific distance away from a type of object, then delete that object. Would using Object.FindObjectsOfType, GetComponent, GameObject.FindGameObjectsWithTag every frame make it run slow?
    There are around 80 objects in the current level I am working on which are grabbed by the World class every frame.

    edit: I just removed the Update () from world, and made sure that none of the objects would be deleted in this level. The frame difference is minimal, around 1 fps...
     
    Last edited: Sep 13, 2014
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    You should use FindObjectsOfType once, not every frame. After calling it, store the results in an array. If the number of objects are dynamic and change frequently, the usual technique is to use a List and have the objects register/unregister themselves as needed.

    --Eric
     
    Draconic and crag like this.
  3. Draconic

    Draconic

    Joined:
    Oct 12, 2013
    Posts:
    82
    Thanks! So something like

    Awake (){
    world.list.Add (this);
    }

    would work for each object? Would they automatically be removed if they were disabled or deleted from the heirarchy?
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Yep.

    Nope. You can use OnDestroy to do world.list.Remove (gameObject) when an object is destroyed.

    --Eric
     
    Draconic likes this.