How Not To Copy Code In Unity

Ben Pielstick
3 min readApr 6, 2021

Often times in programming, you’ll start off doing something with a block of custom code, and then later end up wanting to do something nearly identical. When this happens, the quick solution is to copy the code you already have, and change the few things you needed to do differently and call it done. You can get away with this approximately once. If you end up coming back to this block of code a third time and are considering copying it again, it’s probably time to figure out a way to write shared code that you can call with a different set of parameters, so that it becomes easy to scale without copying the same block of code over and over. If you don’t do this, you risk making your code longer and messier, making it harder to maintain and making you take longer to finish your project in the long run.

Normally you might use something like inheritance to do something like this, allowing several classes to share some of the same properties. Sadly C# doesn’t allow multiple inheritance, but you can use interfaces to do almost the same thing. Unity allows a slight different approach. Since game objects are built out of components, including those for C# scripts, you can attach the same script to multiple game objects, to give them the same functionality without any special code. Using the SerializeField attribute variables can be made to show up in the Inspector panel, allowing different game objects have variables set to different default values even though they’re running the same script.

This…
…leads to this

Unity has another useful feature that helps with these kinds of problems though, and that is the use of Tags.

Any GameObject can have a custom tag assigned to it

Tags can be conditioned against in code from other objects, meaning that even without a C# script, a game object can have different logic run against it, based on a script elsewhere looking up it’s tag.

Just check the tag!

So as you can see, in Unity not only do you have the basic C# features that allow you to easily reuse code, but you also have some custom engine features that allow you to use the same for on multiple different game objects, or even have objects that trigger scripting differently without using any code at all.

--

--

Ben Pielstick

Game developer with over 12 years of experience, mainly focused on MMOs.