Sunday, 22 March 2015

Using Hash values to detect whether the parameters associated with a script have changed

As I am doing work involving procedural content generation, I often want to know whether the parameters associated with a given script have changed.

Although Unity may call Update() or Validate() to indicate that a script may have changed, this causes redundant updates, slowing down interactive updates.

In order to detect whether a variable has changed, a simple pattern can be used:

class X

public var foo
private var _foo

function fooChanged
--- return foo!=_foo

function validate
--- _foo = foo

Often, however, it is expedient to update everything whenever a parameter changes; in this case we do not need to track each variable separately. Instead, a simple checksum can be used:

class Y

public var foo
public var bar

private var _checksum

function hasChanged
--- return checksum() != _checksum

function checksum()
--- return 

function validate
--- _checksum = checksum()

Hash values strings, enums and references

When evaluating a checksum, we need hash values for all parameters. For numbers and vectors, this is straightforward. For strings, enums and references, the following can be used:
  • parseInt(enumVar) => convert an enum value to an int
  • anObject.GetInstanceID() => suitable hash value for any object.
  • anObject.GetHashCode() => suitable hash values for most objects, including strings


No comments:

Post a Comment