How to check if a script component exists before adding it?

I’m checking if a script exists before optionally using it like this:

MyClass myClass = go.AddComponent< MyClass >();
 if(myClass != null){
      // Do some stuff with it if it exists
 }
 else{
      //no worries, continue anyway
 }

But of course, if it doesn’t exist, the main script won’t compile in the first place, with an error:
“The type or namespace name `MyClass’ could not be found. Are you missing a using directive or an assembly reference?”

Is there a way around this?

Thanks

This is tricky. The answer involves using reflection. In general I tend to recommend avoiding reflection. I’ll give you some terms and steps to help your google search. If I get some free time I’ll come back and write the code.

  • Get your type name as a string
  • Check if the type exists
  • Check to see if the type is a component
  • Call add component with your type

Here are a few stack overflow questions to check out.

To invoke a method by string name:

		var assembly = Assembly.GetExecutingAssembly ();
		var types = assembly.GetTypes();
		foreach (var type in types) { 
			var methods = type.GetMethods ();
			foreach (var method in methods) { 
				if (method.Name == "MyMethodTest") { 
					//Run method here
					method.Invoke (null, null);
				}
			}
		}

And to check if a method exists, returning 0 if there are no methods of that name anywhere in your assembly, 1 if there is a single one, and 2 if there are duplicate named ones:

	int MethodExistsOrNot = 0;
	var assembly = Assembly.GetExecutingAssembly ();
	var types = assembly.GetTypes();
	foreach (var type in types) { 
		var methods = type.GetMethods ();
		foreach (var method in methods) { 
			if (method.Name == "MyMethodTest") { 
				//One more MyMethodTest exists
				MethodExistsOrNot += 1;
			}
		}
	}

	if (MethodExistsOrNot > 1) { 
		Debug.Log ("There is more than one existence of this method. Methodname must be unique to invoke from assembly.");
	}
	if (MethodExistsOrNot == 0) {
		Debug.Log ("No method exists in the assembly with that name.");
		MethodExistsOrNot = 0;
	}
	if (MethodExistsOrNot == 1) {
		Debug.Log ("Method exists!");
	}

	Debug.Log (MethodExistsOrNot);

The code will be slow and isn’t optimized, but you can throw that into a function. Call the System.Reflection; namespace at the beginning of your file as well.