Tag Archives: Unity 3D

Quick Tip: Stay in Unity Play Mode while Coding

If you aren’t familiar with Unity, it’s a free game engine with a built-in game editor. I use Unity almost every day, and as you can imagine, I’m coding a lot. Now, when you are writing the majority of code for a game, you are testing things out. Perhaps you want to see how fast is fast enough, or how far is far enough. It can be a pain to enter and exit play mode constantly, but wait!

Unity has a nifty little feature that will recompile code and execute it, even while in play mode. You can easily switch over to Visual Studio (or MonoDevelop) and save your changes. Then you can “Alt + Tab” back over into Unity and quickly see your changes. The only downside to this is that, with large projects (10,000+ lines of C#), this can take a few seconds–even on a really fast machine. However, it’s invaluable when testing things, as you never have to leave your spot in play mode. 😉

Happy coding!

Getting all Objects With the Same Script Attached in Unity

I’ve been working a lot in Unity lately, so I thought I should probably do a few tutorials on scripting in the game engine. One of the biggest helps I’ve gotten in scripting for the game engine (in which I use C#) is a nifty API function Unity provides that allows me to get all the objects with a specific type, i.e. game objects with a specific script attached. Since this is a quick tip, lets skip the behind-the-scenes and logic, and get to the code already!

MyScript[] myScriptObjects =
FindObjectsOfType(typeof(MyScript)) as MyScript[];

This specific function returns a System.Object array of all the Game Objects which have the script MyScript applied. We then cast it so we can get a strongly typed array from the get-go. From here you can access each of these objects in a loop, store them in a generic, etc. Very useful indeed!

Basically the FindObjectsOfType is the same as FindObjectOfType, however, it is probably more useful in most cases I could see it being used since it works with array’s. A good use of this is to perhaps obtain values from each script and add them to a dictionary or list so you can use them, since performing operations en masse could be done just as easily with tags, etc.