как поменять спрайт объекта unity через скрипт
Как менять спрайт при нажатии на toggle через скрипт
Доброго времени суток!
Совсем я пал духом,что прошу помощи у вас
У меня есть два спрайта: sprite1 и sprite2.Задача состоит в том,чтобы при нажатии на toggle менялся спрайт этого ui элемента,т.е. значение у toggle false спрайт меняется на sprite1 и если значение у toggle true спрайт меняется на sprite2
Единственное,что я смог сделать это накинуть background на on value changed в тагле и добавить метод sprite на background
Помогите,пожалуйста! Будете моими героями!
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Несколько Toggle, сделать выбор при нажатии
Добрый день господа. Никак не могу логически домыслить. На сцене есть 9 Toggle. Хочу в потоке.
Как менять картинки на кнопке при нажатии?
как менять картинке на кнопке? (когда нажата одна картинка а когда отпущена другая)
Как при нажатии на кнопку менять текст в окне?
Есть MFC-шное окно с текстом и кнопка, как при нажатии на кнопку, менять текст в окне?
Как менять текст Label при нажатии pushButton?
Хочу сделать так, чтобы при нажатии на определённую кнопку, старый текст Label удалялся и появлялся.
кода метода у меня нет. не знаю как его написать
Добавлено через 10 минут
этот метод находится во вкладке image в on value changed если быть точнее
Да понял, а на чем поменять спрайт?
Добавлено через 9 минут
Даже на чекбоксе меняется. Какой объект перетащите в поле RuntimeOnly на том и поменяетс спрайт. Можно стандартную функцию выбрать Image=>Sprite sprite. Появится поле куда спрайт на который поменять.
Решение
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Как при нажатии на кнопку на главной странице менять текст на другой?
Добрый день, подскажите пожалуйста, как мне в Xamarin при нажатии на кнопку на главной странице.
Как при нажатии на любой блок он должен менять свой фон на серый?
На главной странице два одинаковых сайдбара. Как сделать так что бы при нажатии на любой сайдбар он.
Как без использования js, но с исп. SASS и BS3 динамически менять цветовую схему страницы нажатием toggle на сайте
Кто-то знает как сделать возможность смены цветовой схемы страницы (выбор один из двух вариантов.
Как сделать кнопки, каждая из которых будет менять цвет фона документа при нажатии?
Помогите. Не могу справиться. Нужно написать программу с использованием двух языков: html и.
Как вызвать скрипт при нажатии на кнопку?
Всем приветы! Хлопцы, помогите пожалуйста сделать такую вещь. У нас есть конструкция:
Как изменить спрайты дочерних объектов у префаба через код?
Здравствуйте, пишу игру на Юнити, возникла проблема с префабом.
Изложу вкратце: у меня есть префаб Player. У него есть три дочерних объекта с компонентом SpriteRenderer. Мне нужно через код заменить спрайты у этих объектов. Прилагаю код:
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Не могу изменить scale и position префаба через код
История такая. Я создаю объект из префаба. После чего делаю его дочерним по отношению к другому.
Передача объектов дочерних классов через массив объектов родительского класса в функцию
Здравствуйте. Возможно, вопрос больше относится к теории ООП, но все же я не решился задавать его в.
Ropav90, А что у вас за объект та такой что не появляется. Нажмите «Открыть префаб», сделайте скрин его дочерних объектов
Добавлено через 9 минут
Добавлено через 5 минут
Делаете
Вы их можете хоть сколько делать
Добавлено через 5 минут
Instantiate нужно что бы создать объектhttps://docs.unity3d.com/Scrip. tiate.html
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Как PopupMenu формы убрать у дочерних объектов?
Вопрос следующий: у формы есть PopupMenu1, которое появляется на всех дочерних объектах данной.
Unity как редактировать отдельный компонент префаба через скрипт
имеется префаб Player,мне нужно изменять компоненты Gun1 и Gun2 во время игры, тоесть заменять на.
Чтение модели данных как списка из дочерних объектов
Здравствуйте уважаемые специалисты, Я реализовал два приложения (консольных): 1) реализует Web Api.
Как изменить спрайт объекта через код?
Добрый день. Пытаюсь изменить спрайт объекта через dll. Создаю объект «goPos» в dll, нахожу его и.
Как изменить свойство background у Page через код VB
Всем привет! Появилась необходимость изменить фоновый рисунок page, но как через код VB сделать я.
Game Dev Beginner
How to change a Sprite from a script in Unity (with examples)
In Unity by John French January 9, 2020 16 Comments
Although it’s a simple thing to do, changing a Sprite at runtime in Unity is a question that’s asked surprisingly often.
This may simply be because each developer’s specific needs are different, so it’s not always clear which method is the best or is the most efficient.
However, if you’ve ever tried to load all of the Sprites from a Sprite Sheet into an array from a script, or if you’ve tried to load a Sprite by its filename, what appears to be a simple task can quickly become confusing.
Especially for a beginner, like me.
There are several different uses and multiple methods available for changing sprites at runtime. So I’ve done a little digging and will be exploring each of them, along with their benefits and drawbacks, so that you can more confidently choose which one to use.
Here’s what you’ll learn in this post:
Let’s start with the basics…
How to change a Sprite from a script in Unity
To change a Sprite from a script in Unity, create a reference variable to hold the new Sprite. Then set the Sprite property of the Sprite Renderer Component on the Game Object you wish to change to match the new, replacement Sprite.
In scripting, it looks like this:
In the inspector select the new Sprite that you want to use by dragging it into the field or by using the circle select button.
Select the new Sprite by dragging it into the field or by using Circle Select.
Make sure to also set the Sprite Renderer reference in the Inspector, otherwise you’ll get an error.
Alternatively, if the script is on the same Game Object, you can easily get it by using Get Component in Start.
Then, when you want to change the Sprite, just call the Change Sprite function.
Like in this example if the Left Mouse Button is clicked:
The example will easily change a Sprite Renderer’s existing sprite to use a different one instead. But what if you want to change to one of a number of different Sprites?
What if you have multiple Sprites, such as Slices stored in a Sprite Sheet, and you want to switch to one of them, or all of them in order, or a random Sprite, all from a script?
How to change a Sprite from a Sprite Sheet in Unity
Changing a Sprite to another image from a Sprite Sheet can be done using a similar method as changing a single Sprite.
What’s different is that, in this case, the method of loading the Sprites is different, as you’ll be storing multiple Sprites in an array and retrieving the one that you want with an index.
Creating a Sprite array is simple, just add brackets to the Sprite variable to declare it as an array.
Next we need to add the Sprites to the array.
There are two main ways of doing this. We’ll start with the simplest method first, which is the manual method.
Method #1. The Manual Method
This method works in much the same way as changing a single Sprite, by manually dragging the Sprites to your array in the Inspector.
Drag multiple Sprites to the Sprite array to automatically add them.
It helps to lock the inspector window when doing this, as it’s very easy to accidentally switch to the import settings of the file you’re trying to drag across.
Locking the Inspector makes it easier to add Sprites to the array.
Once the Sprites are loaded into the array you’ll be able to retrieve them using their index, like this:
Simply pass in the array element number in the square brackets that corresponds with the Sprite you wish to switch to.
To check which Sprite is assigned to which element, click the array dropdown in the Inspector.
When to use the manual method
The Manual Method is the simplest way to switch between multiple Sprites and is ideal if you are able to assign the sprites you’re going to use manually in the Inspector. For example, when using a Prefab.
But, what if you want to access Sprites entirely from scripting, without getting a reference to them first?
Well, as it turns out, there is a way to access Sprites from a script by their filename automatically.
Method #2. The Automatic Method
The Automatic Method allows you to access individual Sprites, or even a set of Sprites from a Sprite Sheet, without needing to get a reference to them in the Inspector.
Instead, by using this method, you will be able to load Sprites into a Scene with their filename from the Resources folder, a special folder that Unity will automatically load assets from (even if they’re not referenced in the Scene).
Normally, this is not how Unity works, as assets are usually identified by assigning references to them (as is the case in the Manual Method). As a result, using this method comes with a few words of caution (more on that later) but, if it works for you and your project, and you understand what you’re doing, here’s how to do it.
Add a folder named Resources anywhere in your Assets directory.
Instead of manually adding the Sprites to the array, we can now, instead, load all of the Sprites associated with a Sprite Sheet by using Load All.
In the example above I’ve loaded every file of the type Sprite found in the BirdHeroSprite Texture, which is essentially a directory from which all the Slices are loaded.
While extremely useful, the Resources folder should be used with caution.
Reasons you shouldn’t use the Resources folder
Despite offering a useful option for loading assets, using the Resources folder is, generally, not recommended, as it’s not good practice.
The main reasons you should avoid using the Resources folder in Unity include:
So, while more experienced developers will no doubt understand the risks of using this special folder, and will be able to work around issues like these easily, it’s worth knowing that the general advice is not to use the Resources folder wherever possible.
If the Resources folder isn’t recommended, then why does it exist? And what’s the right way to use it?
When it’s OK to use the Resources folder
According to Unity, there are a couple of use cases for which the Resources folder is particularly useful:
Generally speaking, if your game is small or performance is not (yet) critical to your project, then using the Resources folder isn’t necessarily a problem. For more information on what Unity considers to be best practice when using the Resources folder, see this tutorial.
So what can you do if you want to load a Sprite by its filename, without using the Resources folder?
Well, what if I told you that there is an option that leverages the flexibility of the Resources folder but without the potential drawbacks.
How to load a Sprite from a script by filename (using Addressable Assets)
This method requires a little extra work to set up, but it allows you to load assets into a Scene with a filename and without the drawbacks of the Resources folder.
What are Addressable Assets in Unity?
How to change a Sprite from a Sprite Sheet in scripting using Addressable Assets in Unity:
The asset is now Addressable and can be accessed from a script without a reference.
Using Addressable Assets after using the Resources folder
If you were already using the Resources folder, you may have noticed the Resources directory, and its files, in the Groups Window alongside the Addressable Group. If so, dragging those assets to the Addressable Group will automatically mark them Addressable and move them into a new folder for you (as they can’t stay in Resources for this to work).
How to fix the Invalid Key Exception Error when using Addressable Assets
Depending on your version of Unity, the path that is assigned to the asset may continue to match the string that was being used for the Resources folder value (e.g. BirdHeroSprite, without a folder path or a file extension).
However, if you’re getting an Invalid Key Exception error be sure to check that the Addressable Path (displayed next to the asset’s Addressable Checkbox) matches the value you’re using in the script.
How to access Addressable Sprite Assets from a Script
Now that the Sprites are addressable it’s possible to load them from a script, without a reference. Here’s how to do it:
First, add the following two namespaces to the top of the script. These are required for the Addressable features and loading operations to work properly.
You can add them below the existing namespace declarations, using UnityEngine etc.
Next we need to load the Sprites from the Sprite Sheet, just as we did when using the Resources folder.
This happens in two steps:
In scripting it looks like this:
Instead of setting the contents of the array directly, what’s happening here is we’re starting a loading operation and creating a reference to it (the AsyncOperationHandle). Then when the loading is finished, we’re assigning the result to the Array, using the Handle reference to look up what was loaded.
Doing it in this way allows time for the assets to load.
Registering the function LoadSpritesWhenReady to the spriteHandle.Completed event means that, as soon as the assets are finished loading, the function will be called and the Sprites will be assigned to the Array.
While this part of the method could be done in several ways (inside a Coroutine for example), using an action like this avoids having to repeatedly check in Update, which would inefficient, especially since we know it’s only going to happen once.
Although using Addressable Assets requires more work than simply dropping the Sprites into the Resources folder, it’s more efficient, and it’s a much more up to date solution when compared to using the Resources folder.
A comprehensive guide of the Addressable Asset system is beyond the scope of this article but you can view the full Unity documentation here.
Now that you’ve loaded the Sprites into the Array, it’s time to put them to good use.
How to change a Sprite from an array (3 examples)
Once the Sprites are assigned to the array, you can change the Sprite Renderer’s Sprite property using the same function as in the first example. Simply pass in the name of the array and the index of the Sprite.
For example, to switch to the first Sprite in the array would look like this in scripting:
Or, if you want to switch to a random Sprite simply pass in a random number between zero and the length of the array. Like this:
Lastly, if you want to cycle through each sprite of the array, create an Integer variable to store the last Sprite index. Then increment it every time you change the Sprite:
You’ll notice in the example above that I’ve added an If Statement. This is to check if the index number has reached the end of the array. This is important as trying to retrieve a Sprite outside of the array’s range will result in an error.
Now it’s your turn
Now that you know a bit more about changing Sprites, how will you use what you’ve learned?
Or perhaps you’re still looking for a different method for changing Sprites?
Or maybe you know of a much better method for managing Sprites and are already using it in your game.
Whatever it is, let me know by leaving a comment below.
Масштабирование спрайта либо GameObject Unity3d
Как сделать чтобы размер спрайта был равен заданному значению в пикселях?
Если просто делать
То спрайт просто гигански разбухает и вот почему – у него есть внешнее значение localScale, оно изначально = 1,1,1. Но внутри этого значения сам спрайт уже имеет какой то размер, и это точно не 1х1х1 пиксель, а, допустим, 50х50х1 пикселей. Получается, при данной операции получаем размеры 3500х3500, что разумеется совершенно не нужно.
Вопрос – как получить доступ к внутреннему размеру спрайта, который не в инспекторе изначально 1х1х1, а в проводнике, например 320х160.
Либо, если это не имеет смысла, как просто ровно отмасштабировать спрайт, ровно столько на столько пикселей, сколько мне нужно. Пользуюсь Toolkit2d в Unity, так что подойдут решения и оттуда.
2 ответа 2
Вообще изменить размер спрайта, который уже лежит в юнити нельзя, на сколько я знаю. В смысле тот был 300px и сделать 400px. То есть изменение размеров в игре и экране никак не является следствием увеличения/уменьшения его физически на носителе.
Если хочется менять размер спрайта, отталкиваясь именно от изначального значения, которое значится в инспекторе, то можно попробовать последовать следующим путем:
Размер спрайта можно взять из поля rect класса Sprite, который является, в свою очередь полем sprite класса SpriteRenderer.
Т.е. если у объекта с компонентом SpriteRenderer в скрипте написать так:
то увидим истинные размеры спрайта.
К примеру, хотим уменьшить спрайт по оси X на 100px:
Всё это можно вынести в отдельный метод, как для изменения одной координаты, так и всего спрайта. Это уже на усмотрение. Главное принцип выше.
Unity 2D: работа со спрайтами в разных разрешениях дисплея
Начиная с версии 4.3 в Unity появилась возможность работы с 2D графикой, большая часть новых стандартных решений мне пришлись по душе, потому что я как раз незадолго до этого обновления перешел с Corona SDK.
Но что меня не порадовало, так это отсутствие стандартных инструментов для оптимизации спрайтов под разные разрешения экранов, что имеет довольно таки существенное влияние на производительность на маломощных устройствах.
Конечно, можно использовать что-то похожее на 2D Toolkit для решения этой проблемы, но зачем платить 75$ если можно сделать все самому?
Cо слов пользователей официального форума Unity, разработчики в скором времени не планируют расширять 2D функционал, по крайней мере до релиза 5 версии Unity, и пока что пользователи должны самостоятельно решать данную проблему. Бороздя просторы интернета в надежде найти ответ, я набрел на интересный доклад одного из разработчиков Unity на летней Nordic Game Conference 2014, название говорит само за себя «2D issues and how to solve them». Пользуясь материалами этого доклада, я сделал свое решение проблемы поддержки дисплеев разного разрешения.
Для того чтобы начать, нам нужна только версия атласа спрайтов с самым высоким разрешением, остальные манипуляции с уменьшением качества атласов происходят внутри Unity.
Итак, на первом этапе мы должны организовать атласы спрайтов для разных разрешений: SD, HD, ultra-HD, у нас же будут использованы суффиксы 1x, 2x, 4x.
Берем атлас спрайтов, в нашем случае это ’spritesheet1@4x.png’, в инспекторе выбираем нужные параметры, режем атлас в Sprite Editor, если требуется. Создаем еще две копии атласа в Project Browser (cmd+D, ctrl+D) и переименуем их так, чтобы суффиксы в названии были ‘@2x’, ‘@1x’, меняем свойство Max Size на значение в 2 и в 4 раза меньше соответственно.
Спрайты должны находится в папке Resources, если таковой не имеется — создайте. Это позволяет загружать файлы с этой папки во время выполнения программы.
Обращу Ваше внимание на поля Pixels Per Unit и Format, первое поможет подобрать размер спрайтов под размеры сцены без изменения scale, а второе является очень важным для правильной передачи цвета, размера билда и использования ресурсов графического процессора. На эту тему есть замечательный мануал
Тут все просто, мы собираем игровой объект на основе атласа спрайтов с суффиксом ‘@2x’, добавляем анимацию и любые другие фишки, которые могут вам понадобится. Сохраняем объект как префаб.
Суффикс ‘@2x’ был выбран, потому что большая часть устройств имеют hd разрешение, нам не придется делать лишнюю работу в большинстве случаев.
Скрипт будет работать с любым количеством компонентов SpriteRenderer. Он не будет влиять ни на анимацию, ни на что другое, главное чтобы имена спрайтов в атласе и SpriteRenderer`е были одинаковыми. Данную особенность можно применять не только для смены разрешения спрайтов, но и для замены их на полностью другие, например при создании другого скина персонажа.
Основной принцип работы скрипта таков: у нас есть публичная переменная spriteSheet, в которой мы передаем имя атласа, в котором находятся спрайты нашего объекта.
С помощью метода GetQuality узнаем с каким дисплеем мы имеем дело (для моих целей было достаточно ориентироваться на высоту экрана).
Потом в методе ManageQuality, имея данные о разрешении экрана, загружаем в массив sprites все спрайты нужного нам атласа с правильным суффиксом. В массив renderers загружаем все компоненты SpriteRenderer, которые находятся в объекте. Ищем в массиве sprites спрайт по имени и присваиваем его спрайту компонента SpriteRenderer, если такой существует. Завершает все Resources.UnloadUnusedAssets (), этот метод выгружает из памяти неиспользуемые ассеты.
Также этот скрипт можно использовать для изменения всех спрайтов в сцене. Для этого создаем новый объект, например SpriteManager, и добавляем к нему данный скрипт, но с измененным определением массива renderers:
Спасибо за внимание, надеюсь статья была вам полезна.