Keith Power
Keith Power

Reputation: 14151

Unity Instantiate and add reference to original GameObject

I am making a clone of an Image as it is being touched. I set the original image inactive while the clone is being dragged.

I want however to reactivate the original image from when the clone image is destroyed from the clones script.

Can I add a reference to the original image to the clone when I am instantiating it. I tried a search for the orignial using GameObject original = transform.Find(transform.gameObject.name).gameObject; but I think you cannot find deactivated GameObjects

public void OnPointerDown(PointerEventData eventData)
{
    if (this.gameObject.tag != "Clone")
    {
        clone = Instantiate(this.gameObject) as GameObject;
        clone.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false);
        clone.transform.position = transform.position;
        clone.transform.localScale += new Vector3(0.5F, 0.5F, 0);
        clone.gameObject.tag = "Clone";
        clone.gameObject.name = transform.gameObject.name;

}

Upvotes: 0

Views: 873

Answers (2)

You already have access to it...just save it.

public void OnPointerDown(PointerEventData eventData)
{
    if (this.gameObject.tag != "Clone")
    {
        clone = Instantiate(this.gameObject) as GameObject;
        clone.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas").transform, false);
        clone.transform.position = transform.position;
        clone.transform.localScale += new Vector3(0.5F, 0.5F, 0);
        clone.gameObject.tag = "Clone";
        clone.gameObject.name = transform.gameObject.name;
        clone.GetComponent<TheCloneScript>().original = this.gameObject; //that's it
    }
}

Upvotes: 1

Ariel Gueta
Ariel Gueta

Reputation: 106

As far as I know, you can't find and reference inactive gameobj in the scene. but i did some tests in unity to try and find inactive gameobject and i found this:

if the original obj have a parent, you can find the parent and then find the inactive child like this:

GameObject parent = GameObject.Find("test");
GameObject inActiveChild = go.transform.Find("subTest").gameObject;
inActiveChild .SetActive(true);

or you can just reference the original obj while its still active and use it when needed to active the obj again.

Upvotes: 0

Related Questions