Forked from bcatcho/SetMaterialWithSpriteEditorWindow.cs
Last active
August 29, 2015 14:16
-
-
Save ashumeow/ba4572d1eab133831ebf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEditor; | |
namespace CatchCo.EditorScripts.Util | |
{ | |
public class SetMaterialWithSpriteEditorWindow : EditorWindow | |
{ | |
private Material _material; | |
private bool _needsPositionUpdated; | |
// Add a menu item called "Double Mass" to a Rigidbody's context menu. | |
[MenuItem ("CONTEXT/Material/Set With Sprite")] | |
static void SetToSprite(MenuCommand command) | |
{ | |
var rect = new Rect(0, 0, 100f, 100f); | |
var window = EditorWindow.GetWindowWithRect<SetMaterialWithSpriteEditorWindow>(rect, false, "Set With Sprite", true); | |
window._material = (Material)command.context; | |
window._needsPositionUpdated = true; | |
} | |
public void OnGUI() | |
{ | |
// first OnGUI, set the window to where the mouse is | |
if (_needsPositionUpdated) | |
{ | |
var screenPos = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); | |
position = new Rect(screenPos.x, screenPos.y, 100f, 100f); | |
_needsPositionUpdated = false; | |
} | |
// Set a ridiculous color to make it noticeable | |
var previousColor = GUI.backgroundColor; | |
GUI.backgroundColor = new Color32(255, 98, 95, 255); | |
if (GUILayout.Button("Choose sprite", GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true))) | |
{ | |
ShowPicker(); | |
} | |
GUI.backgroundColor = previousColor; | |
if (Event.current.commandName == "ObjectSelectorUpdated") | |
{ | |
var sprite = (Sprite)EditorGUIUtility.GetObjectPickerObject(); | |
UpdateWithSprite(sprite); | |
} | |
if (Event.current.keyCode == KeyCode.Escape || Event.current.commandName == "ObjectSelectorClosed") | |
{ | |
Close(); | |
} | |
} | |
private void ShowPicker() | |
{ | |
int controlID = EditorGUIUtility.GetControlID(FocusType.Passive); | |
EditorGUIUtility.ShowObjectPicker<Sprite>(null, false, "", controlID); | |
} | |
private void UpdateWithSprite(Sprite sprite) | |
{ | |
if (sprite == null) | |
return; | |
var rect = sprite.textureRect; | |
var texSize = new Vector2(sprite.texture.width, sprite.texture.height); | |
var tiling = new Vector2(rect.width / texSize.x, rect.height / texSize.y); | |
var offset = new Vector2(rect.x / texSize.x, rect.y / texSize.y); | |
_material.mainTextureOffset = offset; | |
_material.mainTextureScale = tiling; | |
_material.mainTexture = sprite.texture; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment