1
\$\begingroup\$

Since Destroy happens after the update cycle, I wonder if you could accidentally (or intentionally) change what gets destroyed since you can still have code execute after calling Destroy.

For instance, say you have a sphere and a cube in your scene, and this script:

public class testDestroy : MonoBehaviour
{
    [SerializeField] GameObject sphere;
    [SerializeField] GameObject cube;

    private GameObject myRef;

    private void Start()
    {
        myRef = sphere;
    }

    public void DestroyTheObject()
    {
        Destroy(myRef);

        myRef = cube;
    }
}

At first myRef is set to the sphere. You can see that myRef is the object set to be destroyed, but then the next line changes the value of myRef. Will the sphere or the cube get destroyed? Does it destroy the value or the reference?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Note that the method signature itself answers this. If Destroy(foo) were aware what variable was holding the value passed to it, it would read Destroy(ref foo). Without that ref, the function sees only the value contained in foo, it does not get a reference to the variable foo itself. \$\endgroup\$
    – DMGregory
    Commented May 17 at 21:50

1 Answer 1

4
\$\begingroup\$

I went ahead and set this up and tested it myself to confirm, and figured I'd post the question in case anyone else was wondering the same.

The answer is that the sphere gets destroyed. The thing being destroyed is the value that was passed to Destroy, not the reference that was pointing to it at the time.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .