Question

I'm currently trying to incorporate dynamic footstep audio into my game. Heres some code for now:

class MyClass
{
    vector< unique_ptr <Sound> > footstep_a;
    vector< unique_ptr <Sound> > footstep_b;
    vector< unique_ptr <Sound> > footstep_c;
    vector< Sound > currentfootsteps;
}

So basically what I want to do is assign one of the footstep_ vectors to currentfootsteps so that I can then have:

if( walkingarea == a )
    currentfootsteps = a;
else ......

I've tried doing the following, but it just throws up a million errors about vectors and such:

if ( walkingarea == a )
    currentfootsteps.clear();
    for(int i = 0; i < footstep_a.size(); i++)
        currentfootsteps.push_back( footstep_a[i] );

Can anyone help me?

Was it helpful?

Solution

I don't really understand what you're trying to do, but assuming the Sound class is copyable, this will compile:

currentfootsteps.clear();
for(auto const& up : footstep_a) {
    currentfootsteps.push_back(*up);
}

Note that you're making a copy of each element in footstep_a and adding it to currentfootsteps.

If Sound is move-only, or you want to avoid copies, use this instead:

currentfootsteps.clear();
for(auto&& up : footstep_a) {
    currentfootsteps.push_back(std::move(*up));
}

But it also seems you should be able to avoid all this by making currentfootsteps a pointer, and simply pointing to one of the vectors depending on whatever condition is satisfied.

vector< unique_ptr <Sound> > *currentfootsteps = nullptr;

if ( walkingarea == a ) {
  currentfootsteps = &footstep_a;
} else if ...

OTHER TIPS

As the name sugguested, unique_ptr should be moved rather than be copied in:

currentfootsteps.push_back( footstep_a[i] );

You may try to get the raw pointer with .get() then put it into currentfootsteps. At the mean time you need to ensure the lifetime of the Sound object is long enough.

Because from my understanding, currentfootsteps only hold the reference to those Sound object, while footstep_a, footstep_b, footstep_c actually own them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top