0

I'm working with IMGUI's drag and drop functionality, using its demo as a baseline.

I've initialized my own set of names as a vector, then iterate over it to generate selectable objects which can be dragged and dropped to swap their order using IMGUI's api:

static std::vector<std::string> partyNames =
            {
                "Bobby", "Beatrice", "Betty",
                "Brianna", "Barry", "Bernard",
                "Bibi", "Blaine", "Bryn"
            };

for (int n = 0; n < partyNames.size(); n++)
{
    ImGui::PushID(n);
    ImGui::Selectable(partyNames[n].c_str(), false);

    if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))
    {
        int payloadData = n;
        ImGui::SetDragDropPayload("DND_DEMO_CELL", &payloadData, sizeof(int));

        ImGui::Text("Swap %s", partyNames[n].c_str());
        ImGui::EndDragDropSource();
    }
    if (ImGui::BeginDragDropTarget())
    {
        if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL"))
        {
            IM_ASSERT(payload->DataSize == sizeof(int));
            const int payload_n = *(const int*)payload->Data;

            // Swap
            std::swap(partyNames[n], partyNames[payload_n]);
        }
        ImGui::EndDragDropTarget();
    }
    ImGui::PopID();
}

This particular snippet works, however only because I've made partyNames a static variable. The moment I remove static from partyNames, dragging and dropping the names to swap them no longer works. The names still appear initially in the correct order, but dragging them has no effect.

Having a static vector is not viable since it will constantly be updated in my application, or passed in from another file.

Looking for clarity as to why this is the case, and how I can use a non-static reference instead. Thanks

Z41N
  • 97
  • 10
  • The paradigm suggests you own your data so you are responsible for preserving it somehow. Using `static` ensure the variable has a persistent/global lifetime. In this situation if you remove static the array gets reset every frame so you lose your state. See comment on top of imgui_demo.cpp: ``` // In this demo code, we frequently use 'static' variables inside functions. A static variable persists across calls, // so it is essentially like a global variable but declared inside the scope of the function. We do this as a way to [...] ``` Had to crop text but try to read the full thing. – Omar Jun 26 '23 at 16:54

0 Answers0