Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Set Material on UI Image Component

Discussion in 'Scripting' started by tomraegan, May 23, 2022.

  1. tomraegan

    tomraegan

    Joined:
    Mar 28, 2016
    Posts:
    134
    Can I please get some help adding a material on the fly to this component?

    Code (CSharp):
    1.     public void OnBeginDrag(PointerEventData eventData)
    2.     {
    3.         if (dragDisabled == false)
    4.         {
    5.             sourceCell = GetCell();                  
    6.             draggedItem = gameObject;                                            
    7.             // Create item's icon
    8.             icon = new GameObject();
    9.             icon.transform.SetParent(canvas.transform);
    10.             icon.name = "Moving Icon";
    11.             Image myImage = GetComponent<Image>();
    This all works great, but I want to set the a material to the image as it's created.

    I've tried material = GetComponent<Renderer>().material; and a few other things (not a very good coder) and could use a hand. What code do I need to use to add a material to this image component used in the UI?

    Cheers!
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,150
  3. tomraegan

    tomraegan

    Joined:
    Mar 28, 2016
    Posts:
    134
  4. pixaware_pwedrowski

    pixaware_pwedrowski

    Joined:
    Oct 25, 2018
    Posts:
    116
    Code (CSharp):
    1. Image image = GetComponent<Image>();
    2. image.material = material;
    What about this one?
     
  5. tomraegan

    tomraegan

    Joined:
    Mar 28, 2016
    Posts:
    134
    Thanks.

    I have tried that, but for some reason it doesn't work.

    I guess it's not obvious after all. I'll keep pottering about and hopefully stumble across the reason.
     
    Flofoof likes this.
  6. pixaware_pwedrowski

    pixaware_pwedrowski

    Joined:
    Oct 25, 2018
    Posts:
    116
    You can share more parts of the code regarding your material setting, so we should help you, as changing the material's property works, so the problem doesn't lay here.
     
  7. tomraegan

    tomraegan

    Joined:
    Mar 28, 2016
    Posts:
    134
    Thanks. That's very kind. If I continue to butt my head against a wall, I will post again.
     
    ppartida likes this.
  8. ppartida

    ppartida

    Joined:
    May 3, 2014
    Posts:
    4
  9. Essekappau

    Essekappau

    Joined:
    Apr 17, 2023
    Posts:
    1
    Probably is not necessary anymore.
    But maybe the problem is the import.
    Check if you using "UnityEngine.UIElements" instead of "UnityEngine.UI"