How to execute code in other class as self?

Hey guys, I’m trying to get a usable item system going, but the pawn will actually control it, and it should be the executor. So how do I execute code in the item as the pawn? For example, how do I use the bottom code in the pawn class as the pawn?

/** In weapon */
void UseItemOnce()
/** some code */

/** In weapon subclass */
virtual void UseItemOnce() override
/** some other subclass code */

And I want to avoid doing this in the pawn class:

/** Uses item once
 * @param DesiredItemIndex: Index of desired item to use
void ADHPawn::UseItemOnce(int32 DesiredItemIndex)
	const EUsableItemType ItemType = GetItemType(Inventory[DesiredItemIndex]);

	if (DesiredItemIndex = CurrentItemIndex && Inventory[DesiredItemIndex])
		if (ItemType == EUsableItemType::Weapon_MeleeWeapon)
			/** Melee attack code */
		else if (ItemType == EUsableItemType::Weapon_ProjectileWeapon)
			/** Projectile weapon attack code */

If your inventory contains references to the carried items, you can simply call Inventory[DesiredItemIndex]->UseItemOnce

If your inventory merely contains some data describing the item, you’ll have have to spawn the item before calling UseItOnce on it. (Alternatively, you could make the function static, but having an instance of the item gives you more control in case even items of the same type may differ by some values, such as charges.)

Hello, Dirt113

In this situation, the elegant solution would be to declare a property of the base weapon class:

AMyBaseWeapon* MyBaseWeapon;

Now, assuming that your ProjectileWeapon class is derived from Base Weapon, you can do the following:

MyBaseWeapon = MyProjectileWeaponInstance`;

Now, when you call UseItemOnce() for MyBaseWeapon object, appropriate overridden method will be called depending on the type of the weapon.

Hope this helped!

Have a great day!

Thanks for the help, but not exactly what I was looking for. I meant as in sort of ‘dynamic macros’, but it seems this is the way to do it :smiley:

I thought there was another way to do it, sort of how macros work. Thanks anyways :slight_smile: