Help adding a script to a gameobject during runtime

Hello community! I have this little project of mine I havent been able to complete yet and I was hoping you guys could give me a hand with your expertise.

On a game that runs on Unity 4, I have been trying to add a script to a gameobject during runtime using the following line of code


with no success, after a talk with the devs, they told me to add it to a method called MainCamera which I figured would execute my code whenever the games starts a new instance, I get the following error in the output log:

ERROR: NullReferenceException: Object reference not set to an instance of an object
MainCamera.Start ()

I have checked that the script inheritates from Monobehaviour and it does, I also tested the script using Unity editor and it works flawlessly, I’m new to unity and I dont know what else I could try, any help is appreciated and if I could add any more information to help you help me just comment down below, thanks a lot!


Some things:

First, do not use GameObject.Find() , it consumes a lot of resources as it must iterato among all objects in the scene. Is better to TAG the object and use

wich is more faster. Or find it from another object you already have assignwed to a value using transform.Find or transform.parent or things like this related to hicheracy.

Second, message about null reference errors (so many users come asking for this. Solution:Debugg):

Hello! This is a standard answer.

Before coming Unity answers, you must always google what your error means. And learn that in every error message, it says the line of code where is happening.

Null Reference errors occurs when there is some variable with value null when code tries to read it. You need to learn to find your problem by your own. First, check your error code, it says the line where the problem is. Second, You need to debug the code while running, and check the states of the variables of the line at the moment the error occurs,

I’m sure you will detect what variable value is NULL. Then investigate why.

Look for some tutorials on how to debug code while running on your scripting software if don’t know what I’m talking about.

Third, if the problem is about these things, please comment the answer with more info (post the code where the error ocurs, and try to ding the null reference variable) and will try to help.


Okay, I was able to solve the Nullreference using the following code:

   GameObject gameObject = GameObject.Find("Player0");
    	if (gameObject != null)
    		foreach (object obj in gameObject.transform)
    			Transform transform = (Transform)obj;
    			if ("cloak"))

But the desired gameObject doesn’t change colors like I intend it to, it stays exactly the same, so the script it is not added to it yet, I get no errors from the log. Any clues?