简体   繁体   中英

Unity 'the object of type has been destroyed' error

I'm destroying an object in my game in that method :

public override void triggerAction(GameObject cube)
{
    base.triggerAction(cube);

    if (cube.GetComponent<Cube>().type == type) {
        DestroyObject(cube);
    }
}

and I got an 'The object of type 'Cube' has been destroyed but you are still trying to access it.' error pointing on this method (the first line) :

if (Physics.Raycast(gameObject.transform.position, rayDir, out hit, 1f) && (hit.collider.gameObject.layer == layerMask)) {
        ActionObject obj = hit.collider.gameObject.GetComponent<ActionObject>();
        obj.triggerAction(gameObject);
}

This method is called in an 'Update' loop.

I saw on the net that we have to test if the gameobject is not null, but when I test it, I got the same error on the condition :

if (gameObject != null) { ... }

Thanks for your answers !

EDIT : Here is how I instantiate my object =

public GameObject cube; // I put my prefab in the inspector 
...
GameObject newCube = Instantiate(cube) as GameObject;

我解决了我的问题,这是对象上的委托方法,我刚刚删除了它。

I cannot be sure, but since this method is called in Update , it is possible that you are trying to destroy the same object (actually, component) twice.

The RayCast call only takes colliders in account, so when you delete the Cube component from cube object, unless Cube is the collider, in the next frame, the same object can still be the target of the RayCast . But this time, the object won't have any Cube component on it and you will get the 'The object of type 'Cube' has been destroyed but you are still trying to access it.' error.

To resolve it, you might want to check whether the objects Cube component is null or not, not itself:

if (gameObject.GetComponent<Cube>() != null) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM