Perlin Mountains

Perlin Mountains
Solo project
Unity3D – C#
December 2012

perlin01 perlin02 perlin03

This program was created as a simple test of randomly generating terrain in Unity. The landscape is created from code, rather than being hand-sculpted. This was done to test the viability of such as system for use in larger projects, such as Roadtrip.

Unity includes a heightmap-based terrain system which can be sculpted in the editor. The challenge of this program was in implementing an algorithm for generating 2D Perlin noise in C#. A user-defined seed is used to initialize a random number generator for consistent results. Noise output is used to build a heightmap for the terrain object. The resulting terrain is then painted with different textures based on slope and elevation, and grass detail sprites are added to flatter areas.


Code sample:

public void BuildTerrain()
     _terrain = GetComponent<Terrain>();
     _terrainData = _terrain.terrainData;

     int w = _terrainData.heightmapWidth;
     float[,] heights = _terrainData.GetHeights(0, 0, w, w);

     for (int y = 0; y < w; ++y)
          for (int x = 0; x < w; ++x)
               heights[y, x] = PerlinNoise(x/64f, y/64f);

     _terrainData.SetHeights(0, 0, heights);

Unity – Keeping objects modular WITHOUT SendMessage

An earlier post of mine explained how Unity’s built-in SendMessage() method could be used to help write highly modular components.

However, there are some major disadvantages to SendMessage. One is that it can easily lead to errors that can only be detected at runtime and can be difficult to find. This is because the method to be invoked is passed in to SendMessage as a string, so there is no guarantee that the receiving object has a method with the same name. Unity will print an error if this happens, but only if it actually happens while the game is running in the editor. The other big problem is that SendMessage is slow. Very slow. The general consensus is that sending a message with SendMessage is about 10 times slower than calling a method on the object directly. And it’s even slower on iOS, possibly as much as 100 times slower than a direct call. This makes sense, because SendMessage must use reflection to look up the names of all the methods on all the components on the target object, perform string comparisons, and then invoke the methods on the resulting set of objects.

So SendMessage is slow. What’s the fast way?

Probably the quickest and most elegant design is to create either a base class or interface for components you want to have receive messages, and create virtual methods for each of the messages you’ll send. If you want most or all of your components to be able to receive messages, it might make sense to extend Unity’s base MonoBehavior class with your own methods.

public abstract class MyBaseGameComponent : MonoBehavior
     public virtual void OnUse(Player user) { }
     public virtual void OnHitByBullet(Bullet bullet) { }

A child class can then extend MyBaseGameComponent and be sent messages by normal method calls.
This technique requires a bit more planning, as you need to know what messages you want to send, but it also helps the speed problem dramatically (virtual methods calls have some overhead, but nowhere near as much as SendMessage). Plus, the compiler/IDE will give us an error message if we try to invoke a method that doesn’t exist. Not bad!

Always assume it’s a bug

Do you follow the development of SpyParty? If not, you should! It’s a really cool asymmetrical multiplayer game focused on deception and getting into the opponent’s head. The lead developer has some good thoughts about how to develop games, so there are some really interesting posts to read on his blog. Balancing a 1-on-1 game with completely different gameplay for each player is no easy task, but he’s doing a great job of it.

The other day, he posted an article about tracking down a persistent bug in SpyParty, one that popped up every now and then and caused real problems, but was not easily reproduced. The article does a great job of explaining the difficulties involved in debugging – a task that most players never really think about. Most player-submitted bug reports are along the lines of “I was playing the game and it crashed. Fix it.” Obviously, this is useless to the developers, since they have no way of figuring out what the player was doing when the game crashed. A good bug report should at least try to explain what the player was doing when the bug happened. Even if the player doesn’t know the exact cause, some level of description is needed.

I really like the author’s mantra: “assume it’s a bug”. I’ve had issues in my own work when I made the (incorrect) assumption that the problem I was seeing was the result of some physics engine weirdness or something else outside of my control. But that’s a dangerous mistake to make, and the underlying bug can bloom out into far worse problems when things get more complicated, especially when dealing with a complicated system like a physics engine. Always assume it’s a bug, try to fix it, and keep an eye on it, otherwise you’ll wind up shipping your game with persistent and impossible-to-find bugs.

Unity – Keeping objects modular with SendMessage()

I’m a fan of being modular with my code, so I’ve been breaking up every game object in Roadtrip into a collection of components: the player object has a component to gather input, another to apply walking movement, another to handle flashlight position and state, and so on. Unity seems to be built around the idea of the GameObject as a collection of components, so this works very well for the most part.

The problem with this setup is that you often run into the need for components to communicate – the flashlight component needs to know that the player pressed the key that turns the flashlight on, for example.  So you start creating references to the other components, and pretty soon everything is dependent on everything else and you might as well have written it all as one script in the first place.

Player GameObject open in the inspector

Roadtrip’s player GameObject open in the inspector

Thankfully, Unity has a GameObject method called SendMessage() that helps to solve this issue, and I’ve been using it all over the place in Roadtrip. SendMessage() lets you call a method on all components attached to an object, and it ignores components that don’t have a definition of that method, without causing an error. For example, when the player enters a vehicle, a message is sent out to all components in the player GameObject called “OnEnterVehicle”. The component that handles movement on foot responds by shutting itself off, and the component responsible for flashlight control automatically turns off the light.

After building this system into the core design of the player GameObject, it becomes very easy and straightforward to add new functionality to the player without having to go around changing a bunch of different scripts. It also means far fewer dependencies, which keeps the part of me that insists on modular design very happy. Want to add a radio to the truck that turns on automatically when a player gets in? It’s a simple matter of creating a new component for the radio and having it respond to the OnPlayerEnter message. There’s no need to have the main Truck script hold a reference to the radio. In fact, the radio doesn’t even need a reference to the truck, meaning we could potentially reuse the same script for a standalone radio in the world! How’s that for modular design!