簡體   English   中英

Unity“類型的對象已被破壞”錯誤

[英]Unity 'the object of type has been destroyed' error

我用這種方法在游戲中破壞了一個物體:

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

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

我得到了'The object of type 'Cube' has been destroyed but you are still trying to access it.' 指出此方法錯誤(第一行):

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);
}

在“更新”循環中調用此方法。

我在網上看到我們必須測試gameobject是否不為null,但是當我測試它時,在以下情況下我遇到了相同的錯誤:

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

感謝您的回答!

編輯:這是我如何實例化我的對象=

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

我解決了我的問題,這是對象上的委托方法,我剛剛刪除了它。

我不確定,但是由於此方法是在Update調用的,因此您可能試圖兩次破壞同一對象(實際上是組件)。

RayCast調用僅考慮了對撞機,因此,當您從cube對象中刪除Cube組件時,除非Cube是對撞機,否則在下一幀中,同一對象仍然可以成為RayCast的目標。 但是這次,該對象上沒有任何Cube組件,您將得到'The object of type 'Cube' has been destroyed but you are still trying to access it.' 錯誤。

要解決此問題,您可能需要檢查對象Cube組件是否為null,而不是其本身:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM