Check for matching variable in all scripts in an array

Hi there.

I have 2 scripts that each contain a string array, with the strings being set in the inspector, like this:


  1. Module.js

    public var moduleTags : String;


  1. ModuleConnector.js

    public var connectorTags : String;


In a separate script, I have an array that contains multiple different instances of Module.js, all attached to different game objects (also assigned in the inspector), like this:

var modules	:	Module[];

What I’m trying to do is go through the array of modules and find each one where the moduleTags array has a string that matches a string I provide, then create a new array out of the results.

So far I have this:

import System.Collections.Generic;
import System.Linq;

var modules		:	Module[];
var startModule	:	Module;

function GetRandomWithTag(modules:Module[],tagToMatch:String)
{
	var matchingModules	=	modules.Where(modules.moduleTags.Contains(tagToMatch)).ToArray;
}

This works fine, except for this error:

‘moduleTags’ is not a member of ‘Module’.

After some experimentation it’s because it wants me to specify which object in the array it’s looking for.
For example, this works:

print(modules[0].moduleTags[0]);

But if I don’t tell it which number in the array to look at, for either array, it gives an error.

So with this function here:

    function GetRandomWithTag(modules:Module[],tagToMatch:String)
    {
    	var matchingModules	=	modules.Where(modules.moduleTags.Contains(tagToMatch)).ToArray;
    }

I get an error telling me that moduleTags isn’t a member of modules, because I haven’t specified which module in the array to get that info from, but I need it to fetch that information from all the modules.

So, the question now is, how do I get it to check for the ‘tagToMatch’ in every string in the ‘moduleTags’ array, in every module in the modules array?

I think you misunderstood how LINQ and the Where method work.

Where needs a function as a parameter that is applied to every element in the array. If the function returns true it means that the element matches and is returned, if the function returns false it is not returned.

The correct call would look like this:

var matchingModules = modules.Where(function(m) {
  return m === tagToMatch; // returns true if the tag matches the tagToMatch parameter
});