Wizard для заполнения массива текстурок

Раздел, посвящённый всему, что связано с программированием для Редактора Юнити. Скрипты Редактора, Wizards и прочее.

Wizard для заполнения массива текстурок

Сообщение gnoblin 21 янв 2010, 14:20

Вроде бы я ничего не потерял пока постил :D .

1. Сам визард:
Синтаксис:
Используется cpp
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
/// ######################################################################################################################################################
/// Автор: gnoblin (gnoblin@gmail.com) 21.01.2010
/// ######################################################################################################################################################
/// Выбираем в сцене гейм-объект со скриптом (правда, пока, определенного типа...) в public Texture[] которого лениво перетягивать 10-20-100 текстурок.
/// Запускаем Wizard, перетягиваем в активный слот любую текстурку из набора - жмем кнопку Fill и получаем забитый массив текстурок в скрипте.
/// ######################################################################################################################################################
/// Требования:
/// 1. В скрипте намертво забит тип скрипта, в который мы забиваем текстурки
/// (это, несомненно, минус - который хотелось бы устранить в последующей версии).
/// 2. В скрипте должны присутствовать
/// public Texture[] frames;
/// public int total_cells;
/// 3. Текстурки должны называть "name__00", "name__01"... (название набора, два нижних подчеркивания, номер из двух чисел).
/// ######################################################################################################################################################
public class WizardToFillTexturesForAnimatedTextureWaterWithFrames : ScriptableWizard
{

    public Texture sample_texture;

    [MenuItem("UsefulTools/Fill Texture Wizard")]
    static void CreateWizard()
    {
        ScriptableWizard.DisplayWizard("Fill Textures into AnimatedTextureWaterWithFrames script", typeof(WizardToFillTexturesForAnimatedTextureWaterWithFrames),
        "Fill", "Ok");
       
    }

   
    void OnWizardCreate()
    {
       ///первая кнопка...
    }

    void OnWizardUpdate()
    {
        helpString = "Перетяните сюда текстурку из набора!";
    }

   
    // When the user pressed the "Apply" button OnWizardOtherButton is called.
    void OnWizardOtherButton()
    {

        FillTextures();
    }

    void FillTextures()
    {
        if (Selection.activeTransform == null)
            return;

        AnimatedTextureWaterWithFrames water_script = Selection.activeTransform.GetComponent<AnimatedTextureWaterWithFrames>();

        if (water_script == null)
            return;

        Debug.Log(water_script.total_cells);

        if (sample_texture == null)
            return;

        Debug.Log("sample_texture name " + sample_texture.name);

        int index = sample_texture.name.IndexOf("__");

        string base_name;

        ///##############
        ///
        ///##############
        if (index != -1)
        {
            base_name = sample_texture.name.Substring(0, index);
            Debug.Log(base_name);

            water_script.frames = new Texture[water_script.total_cells];

            string path = AssetDatabase.GetAssetPath(sample_texture);
            string folder_path = Path.GetDirectoryName(path);
            Debug.Log("path: "+path);
            Debug.Log("folder path: " + folder_path);

            int len = path.Length;
            string extension = path.Substring(len-4,4);
            Debug.Log("Extension: "+extension);

            Texture found_texture;


            for (int a = 0; a < water_script.total_cells; a++)
            {

                string id = a.ToString();
                if (id.Length == 1)
                {
                    id = "0" + id;
                }

                string texture_path_to_search = folder_path + "/" + base_name + "__" + id + extension;
                Debug.Log("Texture path to search: " + texture_path_to_search);

                found_texture = AssetDatabase.LoadAssetAtPath(texture_path_to_search, typeof(Texture)) as Texture;

                if (found_texture != null)
                    Debug.Log("found_texture: " + found_texture.name);
                else
                    Debug.Log("texture not found!");

                water_script.frames[a] = found_texture;

            }

        }

    }
}
 


2. сопутствующий тестовый скрипт:
Синтаксис:
Используется cpp
using UnityEngine;
using System.Collections;

public class AnimatedTextureWaterWithFrames : MonoBehaviour
{

    public Texture[] frames;
    public int total_cells = 16;
   
}
skypeid: madkust
Мои крайние проекты:
Убойный Хоккей
Cube Day Z (альфа)
Аватара пользователя
gnoblin
Адепт
 
Сообщения: 4633
Зарегистрирован: 08 окт 2008, 17:23
Откуда: Минск, Беларусь
Skype: madkust
  • Сайт

Вернуться в Editor

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 2