Как изменить source image unity через скрипт

Дело в том, что мне нужно заменить/удалить картинку в Source Image, в Инспекторе Image, но по непонятной мне причине, сделать я этого не могу. Делаю я это примерно вот так:

Как поменять программно картинку в Image UI?

Дело в том, что мне нужно заменить/удалить картинку в Source Image, в Инспекторе Image, но по непонятной мне причине, сделать я этого не могу.
Делаю я это примерно вот так:

Используется csharp

GetComponent<Image>() //<— вот это строка не даёт мне покоя, так как там нет ни Image ни Source Image, только Sprite.

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

«Улучшение работающего продукта — приводит к его ухудшению.»

Аватара пользователя
GameWorld
Старожил
 
Сообщения: 620
Зарегистрирован: 11 янв 2011, 03:02
Skype: Alien3DModeller

Re: Как поменять программно картинку в Image UI?

Сообщение Tolking 20 янв 2016, 16:02

спрайт используй

Ковчег построил любитель, профессионалы построили Титаник.

Аватара пользователя
Tolking
Адепт
 
Сообщения: 2684
Зарегистрирован: 08 июн 2009, 18:22
Откуда: Тула

Re: Как поменять программно картинку в Image UI?

Сообщение GameWorld 20 янв 2016, 16:33

Приведите хоть строку кода, этой реализации.

«Улучшение работающего продукта — приводит к его ухудшению.»

Аватара пользователя
GameWorld
Старожил
 
Сообщения: 620
Зарегистрирован: 11 янв 2011, 03:02
Skype: Alien3DModeller

Re: Как поменять программно картинку в Image UI?

Сообщение Tolking 20 янв 2016, 18:13

img.sprite = Sprite;

Ковчег построил любитель, профессионалы построили Титаник.

Аватара пользователя
Tolking
Адепт
 
Сообщения: 2684
Зарегистрирован: 08 июн 2009, 18:22
Откуда: Тула

Re: Как поменять программно картинку в Image UI?

Сообщение Harpo 10 фев 2016, 08:06

Используется csharp

   

public Image genderIcon;

    public Sprite maleIcon;
    public Sprite femaleIcon;

где-нибудь в апдейте:

Используется csharp

if(_character.gender == Genders.male)
        {
            genderImage.sprite = maleIcon;
        }
        else if(_character.gender == Genders.female)
        {
            genderImage.sprite = femaleIcon;
        }

Harpo
UNец
 
Сообщения: 7
Зарегистрирован: 10 фев 2016, 07:57


Вернуться в uGUI

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

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



Mifodiy

0 / 0 / 0

Регистрация: 07.04.2016

Сообщений: 3

1

22.10.2018, 13:55. Показов 50774. Ответов 10

Метки image, unity3d, спрайты (Все метки)


День добрый.
В Unity я новичок, в C# тоже, поэтому прошу сильно не пинать.
Сабж.
Есть объект Image, на нем спрайт и рядом кнопка. В папке Assets/Resourses лежат 3 спрайта. Планируется, чтобы при нажатии на кнопку, спрайт менялся циклически на один из трех (1-2-3-1 и т.д.). Но вместо этого изначальный спрайт меняется на белый фон и ничего больше не происходит. Прошу, ткните носом, где я ошибся. Заранее благодарю

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
 
 
 
public class ChangeClass : MonoBehaviour {
    private Sprite spr, spr1, spr2, spr3;
    public GameObject img;
    
    void Start(){
        
        
        img = GameObject.Find("ClassImage");
        spr = img.GetComponent<Image>().sprite;
        spr1 = Resources.Load<Sprite>("mage");
        spr2 = Resources.Load<Sprite>("snipe");
        spr3 = Resources.Load<Sprite>("warrior");
        Debug.Log(spr);
 
        if (spr = spr3) {
            img.GetComponent<Image>().sprite = spr1;
        }
        if (spr = spr1) {
                img.GetComponent<Image>().sprite = spr2;
            }
            else img.GetComponent<Image>().sprite = spr3;
    }
    
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Storm23

Эксперт .NETАвтор FAQ

10365 / 5096 / 1824

Регистрация: 11.01.2015

Сообщений: 6,226

Записей в блоге: 34

22.10.2018, 21:54

2

Mifodiy,
Во-первых, нельзя так сравнивать объекты.
Когда вы загружаете спрайт из ресурсов, создается новый объект. И сравнивать его с объектом в компоненте Image — нет смысла, они всегда будут не равны.
Во-вторых, не нужно завязывать логику приложения на визуальные компоненты и их содержимое.
Нужно создать модель данных и менять ее, а по модели данных уже строить визуальные компоненты.
В вашем случае модель простейшая — это просто номер картинки, которую нужно отображать. Нужно создать отдельное поле типа int, которое будет содержать номер отображаемой картинки и менять его при надобности. И тогда вы будете ориентироваться на ваши данные, а не на содержимое Image.

Вот пример:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using UnityEngine;
using UnityEngine.UI;
 
public class ImageChanger : MonoBehaviour
{
    //index of current image
    public int CurrentImageNumber;
 
    //names of images in Resources folder
    public string[] ImageNames = new string[] {"img1", "img2", "img3"};
 
    void Start ()
    {
        //load CurrentImageNumber from disk
        CurrentImageNumber = PlayerPrefs.GetInt("CurrentImageNumber");
        //show image
        ShowImage();
    }
 
    private void ShowImage()
    {
        //get name of image for CurrentImageNumber
        var name = ImageNames[CurrentImageNumber];
        //set image to Image component
        GetComponent<Image>().sprite = Resources.Load<Sprite>(name);
    }
 
    // Go to next CurrentImageNumber and show image
    // this method is handler of button click
    public void GoToNextImage()
    {
        //next CurrentImageNumber
        CurrentImageNumber = (CurrentImageNumber + 1) % ImageNames.Length;
        //show image
        ShowImage();
        //save CurrentImageNumber to disk
        PlayerPrefs.SetInt("CurrentImageNumber", CurrentImageNumber);
    }
}

Этот скрипт вешается на ваш Image.
А метод GoToNextImage вешается как обработчик на OnClick кнопки:

Изменить спрайт объекта Image



1



0 / 0 / 0

Регистрация: 07.04.2016

Сообщений: 3

22.10.2018, 22:42

 [ТС]

3

Спасибо огромное!



0



0 / 0 / 0

Регистрация: 04.07.2016

Сообщений: 6

11.04.2020, 16:22

4

Можешь про свой скрипт немного рассказать, просто я сейчас по нажатию хочу поменять картинку, но чет не вдупляю, откуда должны браться сами картинки



0



MrFelix

74 / 52 / 25

Регистрация: 08.03.2020

Сообщений: 243

11.04.2020, 16:32

5

Врядли он тебе подскажет, ибо тема 2018 года )
А по поводу картинок:

C#
1
2
3
4
5
[SerializeField] private Sprite[] spriteMassive; //если много картинок нужно или 
[SerializeField] private Sprite oneSprite; //один спрайт
 
yourImage.sprite = spriteMassive[1];
yourImage.sprite = oneSprite;

Добавлено через 52 секунды
PS Ссылки на картинки в испекторе укажешь

Добавлено через 1 минуту
https://habr.com/ru/post/359106/ можно ещё статью почитать



0



Katurina

2 / 2 / 0

Регистрация: 01.02.2017

Сообщений: 16

13.04.2020, 19:22

6

Картинка должна лежать в папке Assets/Resourses в проекте Unity (та на которую меняешь)
Смена происходит кодом:

C#
1
2
public image img;
img.sprite = Resources.Load<Sprite>('имя')

ps При этом надо очень внимательно с именем (одна опечатка и код работать не будет)
(данный пример применяется к объекту Image



0



74 / 52 / 25

Регистрация: 08.03.2020

Сообщений: 243

13.04.2020, 19:58

7

Цитата
Сообщение от Katurina
Посмотреть сообщение

ps При этом надо очень внимательно с именем (одна опечатка и код работать не будет)

Вот именно и вам тоже ))
public Image img;



0



0 / 0 / 0

Регистрация: 13.12.2020

Сообщений: 1

13.12.2020, 11:22

8

Цитата
Сообщение от Storm23
Посмотреть сообщение

Этот скрипт вешается на ваш Image.

Можете кто-нибудь объяснить, как повесить скрипт на Image



0



250 / 186 / 68

Регистрация: 04.03.2019

Сообщений: 1,010

16.12.2020, 23:44

9

JordyBordy, просто потянуть скрипт в нужное место.
2) вариант . ест ькнопка Add Component, там где компоненты все и там выбрать скрипт.



0



0 / 0 / 0

Регистрация: 22.02.2021

Сообщений: 1

22.02.2021, 20:54

10

Добавлено через 2 минуты
При попытке повесить скрипт на Image, пишет ошибку
The script don’t inherit a native class that can manage a script



0



0 / 0 / 0

Регистрация: 05.02.2022

Сообщений: 1

05.02.2022, 18:16

11

это значит, что имя скрипта не совпадает с именем класса



0



Automatic Instantiation

Usually when you want to make a modification to any sort of game assetAny media or data that can be used in your game or Project. An asset may come from a file created outside of Unity, such as a 3D model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
See in Glossary
, you want it to happen at runtime and you want it to be temporary. For example, if your character picks up an invincibility power-up, you might want to change the shaderA small script that contains the mathematical calculations and algorithms for calculating the Color of each pixel rendered, based on the lighting input and the Material configuration. More info
See in Glossary
of the materialAn asset that defines how a surface should be rendered, by including references to the Textures it uses, tiling information, Color tints and more. The available options for a Material depend on which Shader the Material is using. More info
See in Glossary
for the player character to visually demonstrate the invincible state. This action involves modifying the material that’s being used. This modification is not permanent because we don’t want the material to have a different shader when we exit Play Mode.

However, it is possible in Unity to write scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary
that will permanently modify a source asset. Let’s use the above material example as a starting point.

To temporarily change the material’s shader, we change the shader property of the material component.

private var invincibleShader = Shader.Find ("Specular");

function StartInvincibility {
    renderer.material.shader = invincibleShader;
}

When using this script and exiting Play Mode, the state of the material will be reset to whatever it was before entering Play Mode initially. This happens because whenever renderer.material is accessed, the material is automatically instantiated and the instance is returned. This instance is simultaneously and automatically applied to the renderer. So you can make any changes that your heart desires without fear of permanence.

Direct Modification

IMPORTANT NOTE

The method presented below will modify actual source asset files used within Unity. These modifications are not undoable. Use them with caution.

Now let’s say that we don’t want the material to reset when we exit play mode. For this, you can use renderer.sharedMaterial. The sharedMaterial property will return the actual asset used by this renderer (and maybe others).

The code below will permanently change the material to use the Specular shader. It will not reset the material to the state it was in before Play Mode.

private var invincibleShader = Shader.Find ("Specular");

function StartInvincibility {
    renderer.sharedMaterial.shader = invincibleShader;
}

As you can see, making any changes to a sharedMaterial can be both useful and risky. Any change made to a sharedMaterial will be permanent, and not undoable.

Applicable Class Members

The same formula described above can be applied to more than just materials. The full list of assets that follow this convention is as follows:

  • Materials: renderer.material and renderer.sharedMaterial
  • Meshes: meshFilter.meshThe main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
    See in Glossary
    and meshFilter.sharedMesh
  • Physic MaterialsA physics asset for adjusting the friction and bouncing effects of colliding objects. More info
    See in Glossary
    : colliderAn invisible shape that is used to handle physical collisions for an object. A collider doesn’t need to be exactly the same shape as the object’s mesh — a rough approximation is often more efficient and indistinguishable in gameplay. More info
    See in Glossary
    .material and collider.sharedMaterial

Direct Assignment

If you declare a public variable of any above class: Material, Mesh, or Physic Material, and make modifications to the asset using that variable instead of using the relevant class member, you will not receive the benefits of automatic instantiation before the modifications are applied.

Assets that are not automatically instantiated

There are two different assets that are never automatically instantiated when modifying them.

  • Texture2D
  • TerrainData

Any modifications made to these assets through scripting are always permanent, and never undoable. So if you’re changing your terrainThe landscape in your scene. A Terrain GameObject adds a large flat plane to your scene and you can use the Terrain’s Inspector window to create a detailed landscape. More info
See in Glossary
’s heightmapA greyscale Texture that stores height data for an object. Each pixel stores the height difference perpendicular to the face that pixel represents.
See in Glossary
through scripting, you’ll need to account for instantiating and assigning values on your own. Same goes for Textures. If you change the pixelsThe smallest unit in a computer image. Pixel size depends on your screen resolution. Pixel lighting is calculated at every screen pixel. More info
See in Glossary
of a texture file, the change is permanent.

iOS and Android Notes

Texture2D assets are never automatically instantiated when modifying them in iOSApple’s mobile operating system. More info
See in Glossary
and Android projects. Any modifications made to these assets through scripting are always permanent, and never undoable. So if you change the pixels of a texture file, the change is permanent.

Понравилась статья? Поделить с друзьями:
  • Как изменить smx файл
  • Как изменить smsc
  • Как изменить smbios hackintosh
  • Как изменить smartart powerpoint
  • Как изменить smart жесткого диска