How to call a return type function in BeginPlay?

I am trying this function in begin play, how can I do it?

void AMyCharacter::CreateAndApplyNewDynMatInst(UMaterial* Mat, USkeletalMeshComponent* MeshComp , FName SlotName, FName DynInstName)
{
  //My Logic
}

This is not working

void BeginPlay()
{
    Super::BeginPlay();
    CreateAndApplyNewDynMatInst(UMaterial* Mat, USkeletalMeshComponent* MeshComp , FName SlotName, FName DynInstName);
}

I mean no offense, but you need to learn the basic rules of coding, not just related of Unreal Engine, but overall. To understand how function parameters work, what is a return type, etc. Now you’re trying to do a fairly complicated stuff without knowing the basics.

Having parameters in the function means that you have to provide those parameters when you call this function. E.g. you have this function:

void MyFunc(int32 i);

Then, when you want to call it, you provide a real value of that type:

MyFunc(2);

or

int32 index = 2;
MyFunc(index);

What you’re doing makes no sense. Even the compiler will tell you that’s “Illegal use of this type of expression”.

4 Likes

I am doing this:

void AMyCharacter::CreateAndApplyNewDynMatInst(UMaterial* Mat, USKeletalMeshComponent* MeshComp, FName SlotName, FName DynInstName) // Use in or after BeginPlay
{
	// Check for nullptr
	check(Mat); check(MeshComp);
    MeshComp = GetMesh();

	// Create dynamic material instance
	UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(Mat, this, DynInstName );

	// Search material slot by name
	int MatIndex = MeshComp->GetMaterialIndex(SlotName); // 0

	// Check for valid slot
	if(MatIndex != -1)
	{
		// Apply material at index
		MeshComp->SetMaterial(MatIndex, DynamicMaterial);
	}else
	{
		UE_LOG(LogTemp, Error, TEXT("SlotName not found."));
	}
}

There’s a notion of Namespace. Generally speaking, it’s where you can or cannot use certain variables.
If you declare variables in .h, you can use them in any function in your class.
If you have function parameters, you can use them inside that function, but if you try to use them elsewhere, it won’t compile.

Why I’m saying this:
if you have parameters in your function, it generally means that you want to call this function with specific parameters that this function will process. But if you analyze your code, you’ll see that, e.g. USKeletalMeshComponent* MeshComp never uses the value that may be transferred to it when the function is called; no matter what the initial value it, it will still MeshComp = GetMesh();. It means that you don’t need USKeletalMeshComponent* MeshComp as a function parameter.

Same probably goes for UMaterial* Mat. I believe you have already declared the parent material in .h, and set its value somewhere.

3 Likes