Spawned item won't hide

Hey,

I’m trying to create “system” to switch weapons.
I’m spawning all my weapons and set the unused weapons weapon_->bHidden = true; (weapon_ = current weapon AWeapon actor ptr).
The current weapon is attached to my weapon socket on my character.

My weapon switch function:

bool ASTCharacterPlayer::ChangeToCurrentWeapon(int32 index)
{
	if (weapon_slots_[index] == NULL)
	{
		GEngine->AddOnScreenDebugMessage(-1,2.0,FColor::White,FString::Printf(TEXT("no weapon on this slot")));
		return false;
	}

	if (weapon_ != NULL)
	{
		weapon_->bHidden = true;
		weapon_->mesh_->bHiddenInGame = true;
	}


	weapon_ = NULL;
	weapon_ = weapon_slots_[index];
	weapon_->bHidden = false;
	weapon_->mesh_->bHiddenInGame = false;
		
	if (weapon_ == NULL)
	{
		GEngine->AddOnScreenDebugMessage(-1, 2.0, FColor::White, FString::Printf(TEXT("spawned weapon is NULL")));
		return false;
	}

	weapon_->AttachRootComponentTo
		(GetMesh(), FName("weapon_socket"), EAttachLocation::SnapToTarget, false);

	weapon_->AttachMeshToPawn(this);

	return true;
}

the weapon switch works, but the old weapon, remains visible and stays at the position where i switched it.

can anyone help?

Assuming ‘mesh_’ is a UStaticMeshComponenet*, try using weapon_->mesh_->SetHiddenInGame(true). Maybe that will work correctly. Don’t forget to set any Collision components as CollisionComponent->SetCollisionEnabled(ECollisionEnabled::NoCollision) also, or it will block even if invisible.

Also, you are accessing the weapon_ members and setting them before you test it for NULL.

He does check it. He first checks if there is a current weapon, if yes, he tries to make it invisible. Then he set the current weapon to the one from the array " weapon_slots_[index];", and he checked that this is not nullptr in the beginning already. The only thing that is somewhat wrong is the second “null” check at line 21. Because the one at line 3. should already prevent the pointer from being null.

Make sure to use the word “nullptr” instead of “NULL”.

Also, instead of using “bHidden” or “bHiddenIngame”, you should just call “SetVisibility(false);” on the mesh.

weapon_->mesh_->SetVisibilty(false);

// And also disable the collision

weapon_->mesh_->SetCollisionEnabled(ECollisionEnabled::NoCollision);

It is awkward to test whether or not something was in that array at the beginning of the function anyways. Another thread could remove that item from the array between the first check and setting and then accessing the members. So testing the weapon for null first is better than to access any members before testing, becuase it could be possible the weapon_ is still null at that time the members are accessed.

I’m just switching between c++11 and older projects, nullptr/NULL would make no difference anyway in this case, but SetVisibility seems to work, thank you
:slight_smile: