Quick Editor - Generate Hashes

From Unify Community Wiki
Jump to: navigation, search

Hello Everyone,

I would like to share with you a quick script I wrote to generate md5 hashes for an inventory system I was writing. It was important for me to have these hashes for a few reasons.

1) The inventory system was linked to PlayerPrefs. I needed a non-integer way to represent the item.

2) I wanted to use some sort of hash to represent the item as it would prove very difficult for someone to cheat even by modifying PlayerPrefs.

3) The PlayerPrefs keys were also md5 hashes, making reading the PlayerPrefs file impossible.


using UnityEditor;
using UnityEngine;
 
using System.Security.Cryptography;
using System.Text;
 
public class ItemGUID : EditorWindow
{
	// Add menu item named "My Window" to the Window menu
	[MenuItem("UnityExtensions/Generate ItemGUID")]
	public static void ShowWindow()
	{
		MD5 md5Hash = MD5.Create();
		BaseItem[] items = FindSceneObjectsOfType(typeof(BaseItem)) as BaseItem[];
		foreach (BaseItem item in items)
		{
			byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(item.name));
			StringBuilder sBuilder = new StringBuilder();
	        	for (int i = 0; i < data.Length; i++)
	        	{
		            sBuilder.Append(data[i].ToString("x2"));
		        }
 
			item.guid = sBuilder.ToString();
		}
	}
}

In my case, I have an object tree with many GameObjects that represent the Items in my game. Each of these GameObjects have the BaseItem component, which holds the items stats an some utility functions.

It has a public string guid, variable which this editor script sets every-time I run it. As I create new items, I re-run the script which resets all of the guid variable to the md5 hash of its name.

Pretty simple and quick, and most importantly super effective.

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Tools