Common Scripting Pitfalls

From Unify Community Wiki
Revision as of 08:34, 27 June 2006 by Aarku (Talk | contribs)

Jump to: navigation, search

SendMessage and BroadcastMessage

When sending messages, you may find that you sometimes receive the following error messages, even though you're already using SendMessageOptions.DontRequireReceiver to indicate that the message doesn't need to be implemented:

  • SendMessage SomeCoolFunction has no receiver!
  • BroadcastMessage SomeCoolFunction has no receiver!

This may be caused by lines of code such as the following:

<csharp>someGameObject.SendMessage("SomeCoolFunction", SendMessageOptions.DontRequireReceiver);</csharp>

It looks correct, but in fact, we're calling the wrong version of GameObject.SendMessage(). Instead of telling it that we don't require a receiver, we're actually sending the value SendMessageOptions.DontRequireReceiver to SomeCoolFunction() as its function parameter.

The correct form of this method call looks like this:

<csharp>someGameObject.SendMessage("SomeCoolFunction", null, SendMessageOptions.DontRequireReceiver);</csharp>

This time, we're calling the version of GameObject.SendMessage() which has three parameters, and the second parameter is set to 'null'. That means that 'null' is passed to SomeCoolFunction() and the SendMessageOptions.DontRequireReceiver option is correctly interpreted by SendMessage.

This is a common pitfall when writing code that is messaging objects that may not have a receiver.

Floating point variables and methods

A common thing to do in scripting is to Lerp, or linearlly interpolate between two values. Unity has built in functions to lerp variables of type float, Vector3, Color, Material, and Quaternion, to name a few. The key and somewhat confusing thing to realize is that all of the methods that operate on these different classes are within the class itself, except for float. To lerp a float, or to do other common operations dealing with floating point numbers, see the Mathf class. It contains Lerp, Min, Max, Abs, Sin, and all sorts of handy math functions. See the wiki's own Mathfx (short for Mathf eXtended) for even more handy math functions.

Personal tools