How could i optimize this code

I am tring to make game like “Same” but my code is too slow. Its jamming my pc and phone ram usage rising to 700 mb when it stucked.

here is my code. In code, cubess are seeking other cubes that is tagged same. And if there is same cube left side or right side of cube, it is destroying it self and creating another block

function Start () {

}

var sonraki: GameObject;
 function FindMassObj () 
    {
    
    var gos : GameObject[];
    gos = GameObject.FindGameObjectsWithTag("c3"); 
    
    
    
    
    
    for (var go : GameObject in gos)

  { 
   if (go.transform.position.y==transform.position.y) {     
  if (go.transform.position.x-transform.position.x==1 || go.transform.position.x-transform.position.x==-1 ) {   
  
       Destroy (gameObject);
	     
            
            var clone: GameObject;
            clone = Instantiate(sonraki, transform.position, transform.rotation) as GameObject;
  
         }
         }
    } 
    
}
function  Update () {

FindMassObj ();


}

Here are a few things that come to mind:

  1. You could limit the calls to FindMassObj(). If it doesn’t necessarily need to be called every frame, maybe limit it to every 0.25 seconds or so.
  2. Retrieving go.transform.position is more than a simple reference to a variable. It’s backed up by a C# property, and performs some hefty matrix math to calculate the position every single time you request it. Try caching it using Vector3 currentPosition = go.transform.position; and use currentPosition wherever it’s needed.
  3. Cloning and destroying objects is pretty computationally expensive, and becomes a big problem if you’re doing a lot of it. If it applies to your situation, you can use an object ‘pooling system.’ Instead of instantiating and destroying objects at runtime, you can create a pool of objects. Pull an object from the pool and activate it when you need it, then deactivate it and put it back in the pool when you’re done with it.

You could use Raycasts ! :smiley: Much more efficient.

function Update () {
    var leftRay = transform.TransformDirection (Vector3.left);
    var rightRay = transform.TransformDirection (Vector3.right);
    if (Physics.Raycast (transform.position, leftRay, 10)) {
        print ("There is something on the right of the object!");
    } 

    if (Physics.Raycast (transform.position, rightRay, 10)) {
        print ("There is something on the left of the object!");
    } 

}

If you need to access the colliders, check out Physics.Raycast

Just add your if & instantiate codes where they belong.

You will notice two things:

  1. A lot less code

  2. You’re not having to use CPU to check against every single object. Only the ones who are on the left/right :smiley:

I hope this solves your issue .

Good luck, and thanks for using Unity .