Get the image component from the button clicked and create a new gameobject with that image

Hello,

I need some help on instantiation, any help on this will be great. This is the case that I have: I have a button with the image component on it so when I click on the button I would like to create a new object with the image from the button clicked and put this new gameobject as child of another gameobject.

So this is the setup that I have:

So the pratical case is: When I click in PathA button it will create a new gameobject under SelectedGroup gameobject (doesn`t matter the name) with the image component and the image 01A on it.

I have created a function for that but it is cloning everything on root of the scene:

    public void PathFromA()
    {
        Instantiate(gameObject);
    }

Thanks for the help

Images have a .sprite field.

Steps to success:

  • get the Image off the object in question (GetComponent)

  • from the Image get the .sprite

Now you have the Sprite. This may or may not be suitable depending on what you mean by,

You may need to make a SpriteRenderer on a new GameObject and assign that Sprite to it.

Thanks for the information. I think it is something like this (it is giving an error but I think this might be close it it)

    public void PathFromA()
    {
        GameObject newObject = new GameObject("Image");
        Instantiate(newObject.AddComponent<Image>().sprite(PathA.GetComponent<Image>().sprite));
    }

Yeah, don’t do lines like 4… first of all, break it all apart so you can reason about it step by step.

You are already CREATING the new GameObject in line 3, so don’t do any more “instantiating.”

  • add a SpriteRenderer to this new GameObject (keep a reference to it).

  • get the Sprite out of the Image, assign it to a temporary variable.

  • assign the Sprite to the SpriteRender on the new GameObject.

  • move the new GameObject where you want.

When you work like that, each single step can be reasoned about, you can use Debug.Log() to print out what is going on, and when one step fails (which it will!), you know how to track it down.

One
thing
at
a
time.
:slight_smile:

Thanks, Got all the stuff bellow and it is working.

    public void PathFromA()
    {
        GameObject newObject = new GameObject("ImageX");
        newObject.AddComponent<Image>();
        newObject.GetComponent<Image>().sprite = PathA.GetComponent<Image>().sprite;

        GameObject SelectedGroup = GameObject.Find("SelectedGroup");
        newObject.transform.parent = SelectedGroup.transform;
    }

Thank you for guiding me to find the solution. I really appreciated that.