Forewarning, I’m learning UE4 as I go, so if this is a ghastly way for me to approach this, please tell me what the appropriate way would be, and where I should look to find more information on your suggested method.
I’m making a “Character Creation” mechanic for my project. I have an actor component class PlayerCharacterRace, from which I’ve derived blueprints for each race (these will affect stats, materials, starting skills, etc.).
By default, my PlayerCharacter class (actor) has the blank PlayerCharacterRace component attached. During character creation, I’m using a drop down widget to select from the list of races. When selecting a race, it calls a ChangeRace(TSubclassOf<PlayerCharacterRace> NewRace) on my PlayerCharacter class. What I’m trying to do, is delete the “placeholder” PlayerCharacterRace component, and create a new component using the passed TSubclassOf<>. However, either I’m using a very convoluted approach, or I’m missing something extremely obvious…
I’ve used this approach to spawn actors, but can’t get it to work for spawning a component…
Using CreateDefaultSubobject outside constructor is not a best idea, you should use NewObject<> and then AddInstanceComponent()
For new race component you could do NewObject<UPlayerRace>(this, UPlayerRace::StaticClass(), NAME_None, RF_NoFlags, NewRace, false); and NewRace would be your TSubClass<UPlayerRace>, you can assign blueprint of any class that parents from UPlayerRace and spawn it this way.
However you may not actually need to create a new instance/object. Depending on your requirements you may be able to just store the current TSubclassOf and whenever you need to actually access anything use the ClassDefaultObject.
I am not really sure, but I would guess it’s connected to garbage collector and setting up everything created during constructor in editor (if you breakpoint you will see it gets called multiple times even in editor). There is this answer that might help you understand it bit more
Good evening! I tested that method this evening. I didn’t have much luck with it, though I feel I can chalk that up to inexperience and error on my part.
HOWEVER, what I decided to do was cut the whole deleting/instantiating out of the process and tackle something I’d need to learn later on anyway: Data Tables. Rather than blueprinting each race, I’ve decided to expand my PlayerRace C++ to include a USTRUCT that will be used to create a data-table, which will have the exact same structure as the component itself. Upon changing races, I’ll simply have it reference the appropriate row and fill in the racial information using the datatable. Removes unnecessary destroying and instancing of classes, and allowed me to learn a new skill. Can’t beat that!