文章目录

  • 4.1 Python脚本传值到蓝图
  • 4.2 Python脚本调用蓝图自定义函数(Custom Function)
  • 4.3 生成斐波那契数列(1-9) “兔子梯”



本节课将对在虚幻引擎中,如何实现Python脚本传值到蓝图以及调用蓝图自定义函数(Custom Function)进行详解,然后综合运用上述知识在 UE5.0.3 中生成斐波那契数列(1-9) “兔子梯”。


4.1 Python脚本传值到蓝图

Uobject 为例,用法为:uobject.[variable_name] = [python_variable],即直接将 Python 脚本中定义的变量赋值给 Uobject 在蓝图中的变量。
但要注意,Python脚本传值的类型要 UE 蓝图变量基本匹配或者能转化,例如可以将 PythonFloat 类型赋值给蓝图中的 float 类型,也可以将 Python 中的 String 类型赋值给蓝图的 Name 类型结构体。
目前 UnrealEnginPython 插件不支持诸如如数组、映射或 Pythonlistdict等数据结构传值,即便代码不报错也会传入 0空值。想要对这些数据结构进行传值,可以在蓝图内自定义组合结构体的函数

4.2 Python脚本调用蓝图自定义函数(Custom Function)

Uobject 为例,用法为:

  1. 按函数名调用:uobject.call('function arg0 arg1 arg2 ... argN...'),例如:text_render_component.call('SetText Hello')。经UP主这种使用方法在某些情况下会报错,因此不推荐这种用法。
  2. 获取返回值: ret = uobject.call('function, arg0, arg1, ... , argN...),参数量视函数需要调用的参数量而定,例如:actor = uobject.get_owner()
  3. 直接调用 “.call_function”,例如 actor.call_function('MyCustomFunction')

4.3 生成斐波那契数列(1-9) “兔子梯”

  1. 在内容浏览器中 “Content” 目录下新建文件夹,命名为 “UsingBPCustomFunctions”,用来保存后面用到的资产。新建一个关卡 “Basic”并保存。接着新建一个 Actor 类,命名为 “BP_UsingBPCustomFunctions”,用于生成“兔子梯”。然后获取兔子对的静态网格模型 “SM_Two_Bunnies”,添加到 “UsingBPCustomFunctions” 目录下。
  2. UE中的python库 ue4 python api_python

  3. 双击 “BP_UsingBPCustomFunctions”,弹出 “BP_UsingBPCustomFunctions” 资产编辑窗口,在 “组件” 面板添加 一个Python 组件,设置 “Python Module” 为 “tutorial_using_bp_custom_functions”,将 “Python Class” 设置为 “Calclocation”。
  4. UE中的python库 ue4 python api_python_02

  5. 新建 “浮点”类型 变量 “LocationX”、“LocationY” 和 “LocationZ”,用于保存兔子的位置,以及 “变换数组”类型 变量 “Transforms”。
  6. UE中的python库 ue4 python api_Python_03

  7. 新建函数 “SpawnBunny”,为该函数编写蓝图,用于获取“兔子梯”中每个兔子对的位置并根据位置放置静态网格模型。
  8. UE中的python库 ue4 python api_python_04

  9. 新建函数 “AddToTransformArray”,为该函数编写蓝图,用于保存斐波那契数列计算出的每个兔子对的位置。
  10. UE中的python库 ue4 python api_斐波那契数列_05

  11. 新建事件分发器 “onCalcLocation”,并在 “BP_UsingBPCustomFunction” 事件图表界面编写蓝图程序。
  12. UE中的python库 ue4 python api_斐波那契数列_06

  13. 打开 Python Editor新建脚本 tutorial_using_bp_custom_functions,参考UP主在视频中提供的代码。
import unreal_engine as ue

'''斐波那契数列递归定义'''
def fib_recur(n):
	assert n >= 0, "n > 0"
	if n <= 1:
		return n
	return fib_recur(n - 1) + fib_recur(n - 1)

class Calclocation:
	def begin_play(self):
		self.uobject.get_owner().bind_event("OnCalcLocation", self.calc_location)
	
	'''计算每层“兔子梯”中所以兔子对的位置'''
	def calc_location(self):
		Actor = self.uobject.get_owner()	# Python脚本调用蓝图自定义函数的第二种方式--获取返回值
		for i in range(1, 10):
			f = fib_recur(i)
			for j in range(1, f+1):
				Actor.LocationX = i * 100	# Python脚本传值到蓝图
				Actor.LocationY = (f - 1) * (-75) + (j - 1) * 150	# Python脚本传值到蓝图
				Actor.LocationZ = (i - 1) * 150	# Python脚本传值到蓝图
				Actor.call_function('AddToTransformArray')	# Python脚本调用蓝图自定义函数的第三种方式--使用call_function()
  1. 将 “BP_UsingBPCustomFunctions” 置于场景中,运行测试。可以看到“兔子梯”成功生成。
  2. UE中的python库 ue4 python api_Python_07


  3. UE中的python库 ue4 python api_ue5_08


  4. UE中的python库 ue4 python api_Python_09