Как сделать скины в unity
Перейти к содержимому

Как сделать скины в unity

  • автор:

GUI Скин

GUISkins are a collection of GUIStyles that can be applied to your GUI. Each Control type has its own Style definition. Skins are intended to allow you to apply style to an entire UI, instead of a single Control by itself.

A GUI Skin as seen in the Inspector

To create a GUISkin, select Assets->Create->GUI Skin from the menubar.

Please Note: This page refers to part of the IMGUI system, which is a scripting-only UI system. Unity has a full GameObject-based UI system which you may prefer to use. It allows you to design and edit user interface elements as visible objects in the scene view. See the UI System Manual for more information.

Свойства

Каждое свойство GUISkin содержит индивидуальный GUIStyle. Please read the GUIStyle page for more information about how to use Styles. Пожалуйста, прочитайте GUIStyle для получения дополнительной информации о том, как использовать Styles.

Свойство: Функция:
Font Глобальный Font для каждого элемента GUI.
Box Style, используемый для каждого Button
Button Style, используемый для каждого Button
Toggle Style, используемый для каждого Toggle
Label Style, используемый для каждого Label
Text Field Style, используемый для каждого Text Fields
Text Area Style, используемый для каждого Text Areas
Window Style используемый для всех Window
Horizontal Slider Style, используемый для каждого Horizontal Slider
Horizontal Slider Thumb Style, используемый для каждого Horizontal Slider Thumb Buttons
Vertical Slider Style, используемый для каждого Vertical Slider
Vertical Slider Thumb Style, используемый для каждого Vertical Slider Thumb Button
Horizontal Scrollbar Style, используемый для каждого Horizontal Scrollbar
Horizontal Scrollbar Thumb Style, используемый для каждого Horizontal Scrollbar Thumb Button
Horizontal Scrollbar Left Button Style, используемый для Left Button у каждого Horizontal Scrollbar
Horizontal Scrollbar Right Button Style, используемый для Right Button у каждого Horizontal Scrollbar
Vertical Scrollbar Style, используемый для каждого Vertical Scrollbar
Vertical Scrollbar Thumb Style, используемый для каждого Vertical Scrollbar Thumb Button
Vertical Scrollbar Up Button Style, используемый для Up Button у каждого Horizontal Scrollbar
Vertical Scrollbar Down Button Style, используемый для Down Button у каждого Vertical Scrollbar
Custom 1–20 Дополнительный Style, который может быть применён к любому Control
Custom Styles Массив дополнительных Style, которые могут быть применены к любому элементу GUI
Settings Дополнительные Settings для всех GUI
Double Click Selects Word Если опция включена, то дважды нажимая на слово, оно будет выделено
Triple Click Selects Line Если опция включена, то трижды нажимая на слово, будет выделена вся строка
Cursor Color Цвет курсора клавиатуры
Cursor Flash Speed Скорость, с которой курсор будет моргать при редактировании в любом Text элементе
Selection Color Цвет выделенной области текста

Детали

Когда вы создаёте GUI для вашей игры, вам, вероятно, нужно сделать много настроек для каждого элемента GUI. В разных жанрах игры, таких как стратегия или ролевая игра, есть необходимость практически в каждом типе элементов GUI.

Because each individual Control uses a particular Style, it does not make sense to create a dozen-plus individual Styles and assign them all manually. GUI Skins take care of this problem for you. By creating a GUI Skin, you have a pre-defined collection of Styles for every individual Control. You then apply the Skin with a single line of code, which eliminates the need to manually specify the Style of each individual Control.

Creating GUISkins

GUISkins are asset files. To create a GUI Skin, select Assets->Create->GUI Skin from the menubar. This will put a new GUISkin in your Project View.

A new GUISkin file in the Project View

Editing GUISkins

After you have created a GUISkin, you can edit all of the Styles it contains in the Inspector. For example, the Text Field Style will be applied to all Text Field Controls.

Editing the Text Field Style in a GUISkin

No matter how many Text Fields you create in your script, they will all use this Style. Of course, you have control over changing the styles of one Text Field over the other if you wish. We’ll discuss how that is done next.

Applying GUISkins

To apply a GUISkin to your GUI, you must use a simple script to read and apply the Skin to your Controls.

 // Create a public variable where we can assign the GUISkin var customSkin : GUISkin; // Apply the Skin in our OnGUI() function function OnGUI () < GUI.skin = customSkin; // Now create any Controls you like, and they will be displayed with the custom Skin GUILayout.Button ("I am a re-Skinned Button"); // You can change or remove the skin for some Controls but not others GUI.skin = null; // Any Controls created here will use the default Skin and not the custom Skin GUILayout.Button ("This Button uses the default UnityGUI Skin"); >

In some cases you want to have two of the same Control with different Styles. For this, it does not make sense to create a new Skin and re-assign it. Instead, you use one of the Custom Styles in the skin. Provide a Name for the custom Style, and you can use that name as the last argument of the individual Control.

 // One of the custom Styles in this Skin has the name "MyCustomControl" var customSkin : GUISkin; function OnGUI () < GUI.skin = customSkin; // We provide the name of the Style we want to use as the last argument of the Control function GUILayout.Button ("I am a custom styled Button", "MyCustomControl"); // We can also ignore the Custom Style, and use the Skin's default Button Style GUILayout.Button ("I am the Skin's Button Style"); >

For more information about working with GUIStyles, please read the GUIStyle page. For more information about using UnityGUI, please read the GUI Scripting Guide.

Как реализовать смену скина персонажа?

618e9e7fdde78560608372.png

В общем ребят подскажите как можно реализовать смену 3д модели куба. В меню игры выбирается скин и выбранный записывается в PlayerPrefs.SetInt(«Skin»,n); где n номер скина.
При старте сцены уровня в зависимости от значения активируется тот или иной скин. Тоесть у меня как бы префабы скинов фактически они все одинаковые только модель и некоторые данные разные. Как можно изменять саму 3д модель что бы не врубать вырубать префаб скина? Вот так тип скины выглядят

  • Вопрос задан более года назад
  • 167 просмотров

9 комментариев

Простой 9 комментариев

LittleBob

Имеете в виду изменять «спрайт» куба, а не включать новый и выключать старый? Немного не понял вопроса

KraGenDeveloper

~KraGen~ @KraGenDeveloper Автор вопроса
LittleBob, не спрайт а 3д модель, заменять

LittleBob

KraGenDeveloper, мне кажется это невозможно, нужна ведь другая модель. Просто при нажатии на кнопку сохраняй, отключай старую модель и включай новую. Или такой вариант не катит?

KraGenDeveloper

~KraGen~ @KraGenDeveloper Автор вопроса

LittleBob, у меня сейчас так и работает, но при добавлении нового скина нужно много перекидывать добавлять и т.д.

LittleBob

KraGenDeveloper, думаю есть более эффективный вариант, просто знаний не хватает. И я вам ничем помочь не смогу, к сожалению(

Магазин скинов?

Доброго времени суток! Так то я новичок, но хочу спросить, как решить ситуацию. Я создал магазин скинов для 3д персонажа, и с его реализацией у меня возникли проблемы:
1. Когда я нажимаю «Купить» (кнопка у меня позначена ценой скина) то появляется кнопка «Equip», где после ее нажатия ничего не происходит.
2. По каким то причинам скин, выбранный мною, не отображается на самом персонаже. У меня 2 кода: магазин, появление скина на персонаже.
Буду рад помощи!

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SkinControl : MonoBehaviour < public int skinNum; public Button buyButton; public Image iLock; public int price; public Sprite buySkin; public Sprite equipped; public Sprite equip; public Sprite falseLock; public Sprite trueLock; public Image[] skins; private void Start() < if (PlayerPrefs.GetInt("skin1" + "buy") == 0) < foreach (Image img in skins) < if ("skin1" == img.name) < PlayerPrefs.SetInt("skin1" + "buy", 1); PlayerPrefs.SetInt("skin1" + "equip", 1); >else < PlayerPrefs.SetInt(GetComponent().name + "buy", 0); > > > > private void Update() < if (PlayerPrefs.GetInt(GetComponent().name + "buy") == 0) < iLock.GetComponent().sprite = falseLock; buyButton.GetComponent().sprite = buySkin; > else if (PlayerPrefs.GetInt(GetComponent().name + "buy") == 1) < iLock.GetComponent().sprite = trueLock; if (PlayerPrefs.GetInt(GetComponent().name + "equip") == 1) < buyButton.GetComponent().sprite = equipped; > else if (PlayerPrefs.GetInt(GetComponent().name + "equip") == 0) < buyButton.GetComponent().sprite = equip; > > > public void buy() < if (PlayerPrefs.GetInt(GetComponent().name + "buy") == 0) < if (Money.money >= price) < iLock.GetComponent().sprite = trueLock; buyButton.GetComponent().sprite = equipped; PlayerPrefs.SetInt("Money", PlayerPrefs.GetInt("Money") - price); PlayerPrefs.SetInt(GetComponent().name + "buy", 1); PlayerPrefs.SetInt("skinNum", skinNum); foreach (Image img in skins) < if (GetComponent().name == img.name) < PlayerPrefs.SetInt(GetComponent().name + "equip", 1); > else < PlayerPrefs.SetInt(img.name + "equip", 0); >> > > else if (PlayerPrefs.GetInt(GetComponent().name + "buy") == 1) < iLock.GetComponent().sprite = trueLock; buyButton.GetComponent().sprite = equipped; PlayerPrefs.SetInt(GetComponent().name + "equip", 1); PlayerPrefs.SetInt("skinNum", skinNum); foreach (Image img in skins) < if (GetComponent().name == img.name) < PlayerPrefs.SetInt(GetComponent().name + "equip", 1); > else < PlayerPrefs.SetInt(img.name + "equip", 0); >> > > >

Появление скина:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class SS : MonoBehaviour < // Start is called before the first frame update public Transform player; public void Awake() < for (int i = 0; i < player.childCount; i++) player.GetChild(i).gameObject.SetActive(false); player.GetChild(PlayerPrefs.GetInt("skinNum")).gameObject.SetActive(true); >>
  • Вопрос задан более года назад
  • 187 просмотров

6 комментариев

Простой 6 комментариев

Создание магазина с скинами

Расскажите как сделать магазин с бесплатными скинами, с возможностью смены скина и отображения его в игре.

Лучшие ответы ( 2 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Создание магазина с игровыми скинами(смена персонажа)
Подскажите, как мне реализовать магазин с возможность покупки скинов за игровую валюту?

Создание магазина
Здраствуйте уважаемые форумчане-программисты. Такой вопрос. Есть у нас сайт по производству.

Разобраться со скинами
Создал программу с использованием ALphaSkins. Но после переустановки Delphi 7. При открытии.

Создание интернет магазина
Тем кто не разбирается в созданиях сайта прошу вообще не останавливаться и листать дальше, т.к.

Создание Интернет магазина.
Доброе время суток ! Уважаемые форумчане подскажите хорошую, мощную программу для создания.

95 / 60 / 36
Регистрация: 07.08.2013
Сообщений: 241

Лучший ответ

Сообщение было отмечено goodrogrammer как решение

Решение

очень обширный вопрос.
разбейте его на категории. самому легче станет работать.

но для затравки. если скин полностью меняет модельку персонажа, то это просто 10 персонажей настроенных одинаково.
имеют одинаковые структуры поведения и т.д.
затем через true\куплен и false\не куплет в скрипте проверяется можно ли этот скин применить.
по факту просто заменив одну модель на другую. OnDestroy(текущую) и Instantiate(новую).

если же скин просто меняет текстуру модельки, то и того проще.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *