Saturday, May 25, 2013

Cut Paste option in Assets context menu for Unity3D

I have been working with Unity3D from a long time. Its a good engine. I wish I could say its a great engine  but before that I want unity to add a bunch of stuff. One of them is to be able to move assets easily. This simple task becomes very difficult when you are dealing with big project where you have too many assets.

Instead of waiting for unity to do it for me, I wrote a editor script that makes my life easy. This editor script adds Cut & Paste option to Assets context menu.

How to use : Create a c sharp file in editor folder & copy paste the code below. Right click on the asset in Project pane & click on Cut. Then choose the location where you want to paste the asset , right click & select paste.


Code is as follows,,

using UnityEngine;
using UnityEditor;
using System.Collections;

/* Author : Altaf
 * Date : May 20, 2013
 * Purpose : Context menu to copy, cut & paste items
*/

public class AssetHelper : ScriptableWizard
{
    static string _AssetPath = string.Empty;
   
    [MenuItem("Assets/Cut", false, 80)]
    static void MoveAsset ()
    {
        _AssetPath = AssetDatabase.GetAssetPath(Selection.activeObject);
        Debug.Log("Copied asset at path : " + _AssetPath);
    }

    [MenuItem("Assets/Cut", true)]
    static bool MoveAssetValidate ()
    {
        return (Selection.activeObject != null);
    }

    [MenuItem("Assets/Paste", false, 80)]
    static void PasteAsset ()
    {
        string dstPath = AssetDatabase.GetAssetPath(Selection.activeObject);
        string fileExt = System.IO.Path.GetExtension(dstPath);
        if(!string.IsNullOrEmpty(fileExt))
            dstPath = System.IO.Path.GetDirectoryName(dstPath);
        string fileName = System.IO.Path.GetFileName(_AssetPath);
        string msg = AssetDatabase.MoveAsset(_AssetPath, dstPath + "/" + fileName);
        if(string.IsNullOrEmpty(msg))
        {
            _AssetPath = null;
            Debug.Log("Pasted asset at path : " + _AssetPath);
        }
        else
            Debug.LogError("Failed to paste asset : " + msg);
    }

    [MenuItem("Assets/Paste", true)]
    static bool PasteAssetValidate ()
    {
        //Have we copied anything?
        if(string.IsNullOrEmpty(_AssetPath))
            return false;
        //Try to paste no where?
        if(Selection.activeObject == null)
            return false;
        //Trying to paste on same asst again?
        if(AssetDatabase.GetAssetPath(Selection.activeObject) == _AssetPath)
            return false;

        return true;
    }
}



Hope it helps...

No comments:

Post a Comment