Search code examples
unity-game-engineinstantiationitween

Destroy Object and Instansiate it in the middle of Canvas


I have a character that I can drag and drop around the canvas.

If you drag it onto a square, it dissappears.

All of that works well, however I want to Instansiate a clone of that character in the middle of the canvas again once it has been destroyed.

My code to do that so far is;

var clone = Instantiate(gameObject, startPosition, Quaternion.identity);
iTween.ScaleTo(gameObject, new Vector3(0, 0, 0), 2f);
Destroy(gameObject, 3f);

However the object is being cloned I think but I can't see it, and I also have no idea where it is.

Any advice?


Solution

  • UI objects have to be somewhere nested under a Canvas .. if you use Instantiate without passing any parent the GameObject is instantiated on root level without any parent => Your UI stays invisible.

    Either pass it already to Instantiate

    var clone = Instantiate(gameObject, startPosition, Quaternion.identity, parentWithinCanvas.transform);
    

    directly set transform.parent

    clone.transform.parent = parentWithinCanvas.transform;
    

    or use transform.SetParent

    clone.transform.SetParent(parentWithinCanvas.transform, false);
    

    where the last parameter decides whether the object should keeps its current position in the world or not.