HELP Find gameObject With tag in another array

those are my vars…

  var InBag:GameObject[];
  var InBag2:GameObject[];

so i want to find every game object with a certain tag inside the

 var InBag:GameObject[];

and add it to the

var InBag2:GameObject[];

here im with my script

var InBag:GameObject[];
var InBag2:GameObject[];

function Refresh()
{
for(InBag2: GameObject in InBag)
InBag2= GameObject.FindGameObjectsWithTag("Object");
}

1 Answer

1

‘FindGameObjectsWithTag’ searches through all the active game objects in the scene, not through a specified list.

Therefor you need a dynamic list in memory (dynamic in the sense that you dynamically and automatically in Unity’s case assign more memory for your array items as you go along adding more to your list).

import System.Collections.Generic; // Don't forget to place this at top of file!

var InBag:GameObject[];
var InBag2:GameObject[];

// Update the refresh function as follows
function Refresh()
{
    // Prepare a temporary place in memory to add GameObjects to
	var temp : List.<GameObject> = new List.<GameObject>();
    // Go through all GameObjects in InBag
	for(var inBag : GameObject in InBag)
	{
            // Does the tag of the current GameObject 'inBag' equal "Object"?
		if ( inBag.CompareTag("Object") )
			temp.Add(inBag); // It does - so add it to the temporary list
	}

    // Now take all existing GameObjects from the temporary list and export it to a regular built-in array called 'InBag2'
	InBag2 = temp.ToArray();
}

Let me know if this does the trick.

Soppose i use ur first script...how do i put back the stuff inside InBag? cuz its not a ''real array'' compare to the InBag2...?

When are you removing anything from InBag? InBag and InBag2 are both built-in GameObject arrays. What do you need to "put back" into InBag?

InBag=new GameObject[0]; for(var i = 0; i < InBag2.length; i++){InBag+=[InBag2*];}* this was when i used the GameObject.FindGameObjectsWithTag("Object"); i took the items needed and put it inside the InBag2 there i reset the InBag and put back the items that i wanted inside the InBag....but with the script that u showed me...i dont know how to do it

If I understand you correctly, you basically want InBag to have the same items InBag2 has once you remove all the GameObjects tagged "Object". If that is the case, then at the end of 'Refresh()' all you need to do is: InBag=InBag2; (I mean the 'Refresh()' I wrote)