为了满足项目需要,本人需要实现一个c#代码生成器(使用python开发),为此设计了一个语法模板适用于Unity的代码生成器。本次使用了Python的Template模板,使用python开发。
## 开发目标:实现小红帽所挂脚本的自动生成,下图为生成的最终目标
本项目是从json中读取角色场景等信息,因此为了更好地判断所用属性是否需要,设置为bool类型,False表示在c#代码中注释掉该类属性,True代表使用该属性(属性暂时设置为)
Timer = True # 计时器
speed = False # 速度
IsTrigger = True # 触发器
start_point = True # 起始位置
localScale = True # 起始大小
主程序具体python代码如下:
from string import Template
class BuildData:
def Init(self):
# 初始化各类$
Timer = True
speed = False
IsTrigger = True
start_point = True
localScale = True
# 输出a.cs文件
filePath = 'a.cs'
class_file = open(filePath, 'w')
# mycode用来存放生成的代码
mycode = []
# 加载模板文件
template_file = open('TMPL1.tmpl', 'rb')
template_file = template_file.read().decode('utf-8')
tmpl = Template(template_file)
## 模板替换
# 1.需要判断是否使用的模板,不使用的给他注释掉
if(Timer):
TimerContent = ' '
else:
TimerContent = '///'
if (speed):
speedContent = ' '
else: