Cast To in practice: a character that buys furniture
The lesson builds a purchase system with Cast To: the character has a Cash variable and a Purchase custom event with a Price input; a chair Blueprint uses Actor Begin Overlap and Cast to First Person Character and calls Purchase with its price. A Branch checks that the price is not above the cash, so the money never goes negative.
From the course
Taken from the hands-on project of the course; the lessons show every step on video.
What are the steps in the character Blueprint?
- Create a variable Cash of type Float and set it to 1000 in the default value.
- Create a custom event Purchase with a Float input Price. Get Cash, subtract Price, Set Cash with the result and Print String the new value.
What are the steps in the chair Blueprint?
- Turn the chair static mesh from the starter content into a Blueprint, SM Chair Blueprint, and add a Box Collision, enlarged a bit, so the chair is bought when the character touches it.
- In the Event Graph use Actor Begin Overlap and, from Other Actor, Cast to First Person Character. The cast behaves like a Branch: it tests whether the other actor is the character and follows one path if it is, another if it is not.
- From As First Person Character call the Purchase event and set Price to 200.
What do I see?
When the character touches the chair the money shows 800. Each touch subtracts 200 more, 600, 400 and so on, until it goes below zero. That is the problem to solve.
How do I stop the money from going negative?
Right after the Purchase event add a Branch with the condition Price less than or equal to Cash. If true, continue the purchase. If false, print Not Enough Money. Now it counts 800, 600, 400, 200, 0 and then refuses.
Why is it reusable?
A second chair instance can also be bought, because Cast To works with more than one instance of the same Blueprint. A table Blueprint with its own box, Actor Begin Overlap, Cast to First Person Character and a price of 500 works too. Once the purchase logic is in the character Blueprint, you do not change it to add new products.
Free PDFs that go with this page
One-page guides made from the lessons, sent by e-mail.
- Cast, Interface or Event Dispatcher? — A one-page guide to choosing how two Blueprints talk to each other, with the example from the course for each method.
- Blueprint Cheat Sheet — A free one-page PDF for Unreal Engine 4/5, made from the lessons of the course. Keep it next to your editor while you learn.
- Free PDFs
Frequently asked questions
What does Cast to First Person Character do in this example?
It checks that the overlapping actor is the character and gives access to its Purchase event and variables.
Why use a Branch after Purchase?
To compare Price with Cash and avoid negative money.
Can I add more products without changing the character?
Yes. Each product Blueprint casts to the character and calls Purchase with its own price.