If you are learning Unreal Blueprint, you’ve heard about macros and functions but feel confused about them, this is the article for you. You might find this article more helpful if you come from a non-tech background just like me.
Macros vs. Functions
Let’s see what Unreal’s document said:
Macros take the nodes from the macro graph, and actually replace the macro node with a copy of all those nodes.
— — From Blueprint Best Practices
So, macros are just COPY & PASTE! That’s all!
But do you really understand what this means? Here I got an interesting example for you.
I made a function and a macro which look exactly the same. Both contain a for loop from 0 to 5, and jump out of the function/macro when the loop index reaches 3.
And I added a print string connect to the output executions of the function/macro
Can you predict what the output print will be when the Event Construct is connected to the function comparing to when it’s connected to the macro? Will the result be same?
The answer is no. The results are totally different. When we use the function, the loop goes within the function until the index is bigger than 2. When the index is bigger than 2, it jumps out of the function and won’t come back. This is what it prints:
You are in the function loop 0
You are in the function loop 1
You are in the function loop 2
You are in the function loop 3
You are back to Event Construct
When we use the macro, it’s COPY & PASTE, so this is what is actually happening:
And as you can imagine now, the output is:
You are in the function loop 0
You are in the function loop 1
You are in the function loop 2
You are in the function loop 3
You are back to Event Construct
You are in the function loop 4
You are back to Event Construct
You are in the function loop 5
You are back to Event Construct
Hope this example helps you better understand what COPY & PASTE really means.
Because macros are just COPY & PASTE, you can’t target them, like call a macro on another object.
when the Blueprint is compiled, the macro copies all the graph nodes, and pastes them in where the macro node is
— — From Blueprint Best Practices
Another big difference between macros and functions is you can’t place latent nodes in function. Why? Unreal has an official answer here:
A more thorough list of the differences between macros and function can also be found in Blueprint Best Practices.
In summary and practical, this is how I will decide whether I should use macro, function or event:
- Do you need to have latent nodes in it? If yes, exclude function.
- Do you need to call it from another Blueprint or override it in a child Blueprint? If yes, exclude macro.
- Do you want it to return any values? If yes, exclude event.
To be honest, in most of the cases, there are always more than one way that can serve your need, and there are not that much difference.