AddComponent changed after upgrading Unity

I’ve just upgraded from Unity 4 to 5.

It has changed a few lines of code. But the newly generated code is givin warnings.

Let me first show the original code, which worked perfectly fine.

void Start () {

		a1 = gameObject.AddComponent(PlayerPrefs.GetString ("animal1") + "Functions") as IAnimalFunctions;

		currentAnimal = a1;

		Animal1Shape();
	}

I tried to change the code back to this, but it gave me the following error:

Assets/Scripts/Animals/AnimalContainer.cs(21,25): error CS0619: UnityEngine.GameObject.AddComponent(string)' is obsolete: GameObject.AddComponent with string argument has been deprecated. Use GameObject.AddComponent() instead. (UnityUpgradable).’

After upgrading, the above was changed into the following.

a1 = UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(gameObject, "Assets/Scripts/Animals/AnimalContainer.cs (16,8)", PlayerPrefs.GetString ("animal1") + "Functions") as IAnimalFunctions;

And this gives me a warning:

[Assets/Scripts/Animals/AnimalContainer.cs (16,8)] Component type ‘SheepFunctions’ found on caller assembly. Consider replacing the call method call with: AddComponent()UnityEngine.Debug:LogWarningFormat(String, Object) UnityEngineInternal.APIUpdaterRuntimeServices:ResolveType(String, Assembly, String) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineInternal/APIUpdaterRuntimeServices.cs:45) UnityEngineInternal.APIUpdaterRuntimeServices:AddComponent(GameObject, String, String) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineInternal/APIUpdaterRuntimeServices.cs:27) AnimalContainer:Start() (at Assets/Scripts/Animals/AnimalContainer.cs:16)

The PlayerPrefs.GetString (“animal1”) + “Functions” is equal to “SheepFunctions” which is another class.

How do I fix this problem? :slight_smile:

This may help. http://answers.unity3d.com/answers/923278/view.html

Safe way:

if ("SheepFunctions" == PlayerPrefs.GetString ("animal1") + "Functions") {
  gameObject.AddComponent<SheepFunctions>();
}

Unsafe way:

gameObject.AddComponent(System.Type.GetType(PlayerPrefs.GetString ("animal1") + "Functions"));