简体   繁体   中英

DestroyBlock script destroying all blocks (Unity)

I have been working on a building game and whenever I try to destroy a block all of the blocks that contain the script, DestroyBlock.cs are destroyed. I know why the problem is happening, but I don't know how to fix it. Could anyone please help me? I am trying to get a development build out by this Saturday and I need a quick fix to this.

using UnityEngine;
using System.Collections;

public class DestroyBlock : MonoBehaviour
{
    public static bool IsDestroyable = false;

    void Update ()
    {
        if (Input.GetMouseButtonDown(1) && IsDestroyable == true)
        {
            Destroy(gameObject);
        }
    }

    void OnMouseEnter()
    {
        renderer.material.color = Color.black;
        IsDestroyable = true;
    }

    void OnMouseExit()
    {
        renderer.material.color = Color.white;
        IsDestroyable = false;
    }
}

Okay, so I've looked over the code more, and I'm almost positive the reason this is happening is because your IsDestroyable variable is static. This means a single instance of this is shared between every DestroyBlock object ever created. Any time an instance of DestroyBlock sees that the mouse has entered it, it sets IsDestroyable to true, which means that for every single block in existence IsDestroyable == true . Update is called, and, because there hasn't been a MouseExit yet, all the blocks get destroyed. As it stands, either every block is going to get destroyed or none of them will.

The easiest way to fix this would just be to change IsDestroyable to a non-static property.

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