Search Unity

One or many scripts

Discussion in 'Scripting' started by Smagacz, Jan 14, 2017.

  1. Smagacz

    Smagacz

    Joined:
    Feb 10, 2016
    Posts:
    23
    Hi,
    I need to check state of few objects. What is better, attached script with check option to all objects or check it in one script in foreach loop?
     
  2. Dennis59

    Dennis59

    Joined:
    Jan 8, 2013
    Posts:
    66
    Generally I try to put code controlling an object on the object. That makes it much easier to understand why an object is behaving as it does. Especially when you have to look at it a month or two later. One large script is generally harder to decipher than several small and targeted ones. That said, I could envision situations where you would want to test the state in one separate script. It's really up to you.
     
  3. mightybob

    mightybob

    Joined:
    Mar 23, 2014
    Posts:
    75
    Depends on how many objects there is. If there are just a few objects, (like 5-10) just put Update scripts on them.

    If there are hundreds of objects, don't be putting Update scripts on all of them, I'm pretty sure that'll kill performance. It'd be better to make a List of the objects and check them in a for loop.

    If there are thousands of objects, you may want to have the for loop run over several frames. Here's an example of how I did this in one of my projects, where I have thousands of pre-determined chunks that need to be checked.

    Code (CSharp):
    1.     public int chunkIndex = 0;
    2.     public int checksPerFrame = 200;
    3.     void Update() {
    4.         for (int i = 0; i < checksPerFrame; i++) {
    5.             if (chunkIndex + i < chunkMarkers.Count) {
    6.                 //do something with the current object e.g. chunkMarkers [chunkIndex + i].DoSomething();
    7.             }
    8.         }
    9.         chunkIndex += checksPerFrame;
    10.         if (chunkIndex >= chunkMarkers.Count) {
    11.             chunkIndex = 0;
    12.         }
    13.     }
     
    Kiwasi likes this.
  4. Smagacz

    Smagacz

    Joined:
    Feb 10, 2016
    Posts:
    23
    ok, thanks