How do I add a script and assign a reference variable to it in one line?

How do I save a reference to the added script in one line?

SomeScript someScriptRef = someGameObject.GetComponent();

Recently, the string parameter overload of AddComponent was removed, I guess to prevent ambiguity in what it actually was doing with that string. (since for such cases, defining the type makes sense universally, making it fully generic) I hope they don’t mess with GetComponent too much though.


It’s fairly simple actually and is a great thing to do!
If I wanted to add a SomeScript and use it in the next several lines of code, I can do this:

SomeScript myScript = (SomeScript) gameObject.AddComponent(typeof(SomeScript));

Or even

SomeScript myScript = gameObject.AddComponent(typeof(SomeScript)) as SomeScript;

And typeof should work with all classes that can be added as a component!
AddComponent is very much like Instantiate and returns the object it created.

Just in case you wanted to read up on different topics:


AddComponent: Unity - Scripting API: GameObject.AddComponent

As shown in the link above there are three different ways to add and cast the object using <T>, ("string type of T"), and typeof(T) and using the castings shown above.