How to spawn NPCs?

#1

/!\ Possible spoiler ahead /!\
I need help with #28157 (contains spoiler)

To make it work I need to spawn NPC near the player, but what i’ve got so far crashes the game :

        std::shared_ptr<npc> tmp = std::make_shared<npc>();
        tmp->normalize();
        tmp->randomize( NC_CLASSE );
        tmp->spawn_at_precise({ get_levx(), get_levy() }, p);
        return true; 

( [SPOILER] : NC_CLASS is in fact NC_HALLU which is a new class )

So what’s the proper way to spawn an NPC ?

#2

I changed code to :

    if( one_in( 100 ) ) {
        std::shared_ptr<npc> tmp = std::make_shared<npc>();
        tmp->normalize();
        tmp->randomize( NC_CLASS );
        tmp->spawn_at_precise( { get_levx(), get_levy() }, p );
        if( !critter_at( p, true ) ) {
            overmap_buffer.insert_npc( tmp );
            return true;
        } else {
            return false;
        }
    }

And now instead of a hard crash I get :

  DEBUG    : Invalid body part token -858993460
 
 FUNCTION : convert_bp
 FILE     : ..\src\bodypart.cpp
 LINE     : 136

Anybody got any idea on what I’m doing wrong ?

#3

Have you tried to add load_npcs() in the end, like in code to spawn NPC in debug menu?

#4

Just did, it still gives the same error.

#5

Why aren’t you using:

    const string_id<npc_template> npc_template_name( "npc_template_name" );
    const int tmp_id = g->m.place_npc( get_levx(), get_levy(), npc_template_name );
    g->load_npcs();

    return g->find_npc( tmp_id );

I know that works for me.

#6

I’ve made the npc template, and implemented your suggestion but I still get the Invalid body part token error.

What does this errorr mean ? I don’t see where we would/should have touch anything about body part.

#7

Does anybody know what’s the link between bodypart.cpp and spawning an NPC ?

Does the error could come from a mistake in the json ? Even though bodyparts are never adressed in any of them.

EDIT : I haven’t figure where the bodypart error came from but this works as far as spawning NPC is concerned

        std::shared_ptr<npc> tmp = std::make_shared<npc>();
        tmp->normalize();
        tmp->randomize( NC_CLASS );
        tmp->spawn_at_precise( { get_levx(), get_levy() }, tripoint );
        overmap_buffer.insert_npc( tmp );
        load_npcs();