which one of these more effective and memory friendly

hey guys, so i’m wondering about this a while ago, cause of i’m in dev of making an android/iOS game and i don’t want to use up memory for unecessary process
i already googled regarding this, but not yet find any real answer

i got 50+ objects that user can touch/interact with, and everytime user react with it, it’ll do something
so, which one of these code style should i use?

  1. make 1 script and attach to every each object (which meant this script will exist in every 50+ objects) and simply detect the touch and use this.gameobject script to do what it need to do

or

  1. make 1 script manager, which will detect the raycast of the collided object with touch, and then compare the name of the object that got raycasted, after that use gameobject.find to find the gameobject with that name to use the component and do what that object need to do

i assume that the first will be the most effective, but which one is the most memory/process friendly? , i got quite concern about this lately, i don’t know why…

None of this sounds memory intensive.

Though the second sounds like it’ll create a lot of string, and query via ‘Find’. Which beats on the GC and is slow.

1 Like

While #1 sounds like a lot of scripts @lordofduct wrote exactly why you shouldn’t do #2.

I wouldn’t stress too much about memory usage of a script, unless the script has a value that gets repeated in each script and it takes up a lot of memory itself. There is an article in the docs that talks about this sort of thing. Its talking about using a ScriptableObject to store that data, have a look for yourself, it will explain it better than I can.

1 Like

My answer would be, “Code it however feels natural for you and results in readable code,” then pay attention to how well it runs on your target platform, and don’t forget to try and run on lower-end platforms too, if you’re targeting those. Don’t bother with optimization until necessary, IMNSHO.

2 Likes

It doesn’t really matter until you have performance issues. But since I like the exercise…

Preoptimisation is the root of all evil

As written 1 is faster. But there is a faster way. So something like this:

  1. Make one script that manages all of the touch points. Collect references to all of the objects into a data structure like a quad tree on start up. Create a single method that takes the touch position and converts it into the touched object. Manipulate the object as required

But just because something is fast doesn’t mean its the right way to do it. See everyone else’s comments about readable code.

1 Like

hey guys, thank you for all of your reply
if i use 1, the script will not have any information, and it will simply getcomponent script to other object and do stuff accordingly, which is probably the right use of the code style
but i intrigue with the quad tree, somehow i always miss it