【游戏开发创新】Unity游戏c#/cs/csharp垃圾代码生成器,叮,请查收您的一百万行代码

本文介绍了如何使用lua脚本garbage_code_generator.lua生成C#的无意义代码片段,用于Unity游戏中的特定需求。通过设置参数,可以定制类的数量、方法和属性,便于插入到Unity项目中混淆代码。
摘要由CSDN通过智能技术生成

一、前言

点关注不迷路,持续输出Unity干货文章。

嗨,大家好,我是新发。由于一些特殊原因,我们需要在游戏中插入一些c#垃圾代码。
那么,如何生成c#垃圾代码呢,本文介绍的方法是使用一个lua脚本来生成c#垃圾代码,所以,在此之前我们先下载个lua运行环境。

二、安装lua

如果你本地已经下载过lua,跳过此步。
进入lua官网:http://www.lua.org/
点击download
在这里插入图片描述
点击binaries
在这里插入图片描述
选择一个lua版本下载,比如我下载lua 5.3.6
在这里插入图片描述
点击download
在这里插入图片描述
下载完之后我们得到了如下的文件。
在这里插入图片描述
为了方便运行,我们配置一下环境变量。
在这里插入图片描述
然后我们在命令行中执行lua53,如下,则说明环境变量生效了。
在这里插入图片描述
测试一下print("hello lua")
在这里插入图片描述
好了,环境搞定了,接下来就是我们的lua代码了。

三、garbage_code_generater.lua

将文章末尾的lua代码保存为garbage_code_generater.lua
在这里插入图片描述

四、执行

在地址栏中输入cmd回车。
在这里插入图片描述
然后执行如下的命令

lua53 garbage_code_generater.lua -o output -c 100

在这里插入图片描述

参数说明
-h: 帮助
-o: 输出路径, 默认值=“garbate”
-c: 生成类数量, 默认值=400
-mc: 类方法数量, 默认值=30
-pc: 类变量数量, 默认值=30
-ac: 类属性数量, 默认值=30
-verbose: 输出每一个类文件名
-q: 安静模式, 不输出任何东西

执行成功,如下
在这里插入图片描述
可以看到生成了一个output文件夹。
在这里插入图片描述
里面就是生成的cs垃圾代码。
在这里插入图片描述
我们把代码放到Unity工程中。
在这里插入图片描述
反编译一下生成出来的Assembly-CSharp.dll,可以看到,我们的垃圾代码都在dll中了。
在这里插入图片描述

完毕。
喜欢Unity的同学,不要忘记点击关注,如果有什么Unity相关的技术难题,也欢迎留言或私信~


附录:lua代码

local os = os
local math = math
local io = io

math.randomseed(os.time())

local charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_"
local charlist_length = string.len(charlist)

local header_charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
local header_charlist_length = string.len(header_charlist)

local function getChar(chars, charscount, i)
    local idx = i % charscount + 1
    return string.sub(chars, idx, idx);
end

local function getRandomChar()
    return getChar(charlist, charlist_length, math.random(1, charlist_length))
end

local function getRandomHChar()
    return getChar(header_charlist, header_charlist_length, math.random(1, charlist_length))
end

local function getRandomName(l)
    local r = getRandomHChar()
    for _=2, l do
        r = r .. getRandomChar()
    end
    return r
end

local base_type_and_default = {
    ["bool"] = "false",
    ["int"] = "0",
    ["float"] = "0.0f",
    ["double"] = "0.0",
    ["string"] = "null"
}

local base_type_randomfunction =
{
    ["bool"] = function(a, b, c)
        local r = math.random(1, 5)
        if r == 1 then
            return {a .. " = " .. b .. " && " .. c ..";", }
        elseif r == 2 then
            return {
                "if(" .. a .. ") ",
                "{",
                "    ".. b.. " = !" .. c .. ";",
                "}",
            }
        elseif r == 3 then
            return {
                "if(" .. a .. " && " .. c .. ") ",
                "{",
                "    ".. b.. " = !" .. b .. ";",
                "}",
            }
        elseif r == 4 then
            return {
                "if(" .. a .. " || " .. b .. ") ",
                "{",
                "    ".. b.. " = !" .. b .. ";",
                "}",
            }
        elseif r == 5 then
            return {a .. " = " .. b .. " || " .. c ..";", }
        else
            return {a .. " = " .. b .. " && " .. c ..";", }
        end
    end,
    ["int"] = function(a, b, c)
        local r = math.random(1, 7)
        if r==1 then
            return {a .. " = " .. b .. " + " .. c ..";", }
        elseif r==2 then
            return {a .. " = " .. b .. " - " .. c ..";", }
        elseif r==3 then
            return {a .. " = " .. b .. " * " .. c ..";", }
        elseif r==4 then
            return {a .. " = " .. b .. " / " .. c ..";", }
        elseif r==5 then
            return {
                a .. " = " .. math.random(1, 100000) ..";",
                b .. " = " .. math.random(1, 100000) ..";",
                c .. " = " .. math.random(1, 100000) ..";",
            }
        elseif r==6 then
            return {
                "for(int i=0;i<"..a..";++i)",
                "{",
                "	"..b .."+=1;",
                "   "..c .."+=" .. b..";",
                "}",
            }
        else
            return {
                b .. " = " .. a .. ";",
                c .. " = " .. a .. ";",
            }
        end
    end,
    ["float"] = function(a, b, c)
        local r = math.random(1, 6)
        if r==1 then
            return {a .. " = " .. b .. " + " .. c ..";", }
        elseif r==2 then
            return {a .. " = " .. b .. " - " .. c ..";", }
        elseif r==3 then
            return {a .. " = " .. b .. " * " .. c ..";", }
        elseif r==4 then
            return {a .. " = " .. b .. " / " .. c ..";", }
        elseif r==5 then
            return {
                a .. " = " .. math.random(1, 10000) ..".0f;",
                b .. " = " .. math.random(1, 10000) ..".0f;",
                c .. " = " .. math.random(1, 10000) ..".0f;",
            }
        else
            return {
                b .. " = " .. a .. ";",
                c .. " = " .. a .. ";",
            }
        end
    end,
    ["double"] = function(a, b, c)
        local r = math.random(1, 6)
        if r==1 then
            return {a .. " = " .. b .. " + " .. c ..";", }
        elseif r==2 then
            return {a .. " = " .. b .. " - " .. c ..";", }
        elseif r==3 then
            return {a .. " = " .. b .. " * " .. c ..";", }
        elseif r==4 then
            return {a .. " = " .. b .. " / " .. c ..";", }
        elseif r==5 then
            return {
                a .. " = " .. math.random(1, 10000) ..".0;",
                b .. " = " .. math.random(1, 10000) ..".0;",
                c .. " = " .. math.random(1, 10000) ..".0;",
            }
        else
            return {
                b .. " = " .. a .. ";",
                c .. " = " .. a .. ";",
            }
        end
    end,
    ["string"] = function(a, b, c)
        local r = math.random(1, 3)
        if r==1 then
            return {a .. " = " .. b .. " + " .. c ..";", }
        elseif r==2 then
            return {
                a .. " = string.Format("..c ..","..b..");",
            }
        else
            return {
                b .. " = " .. a .. ";",
                c .. " = " .. a .. ";",
            }
        end
    end,
}

local base_type_list = nil
local function getRandomType()
    if base_type_list == nil then
        base_type_list = {}
        for k, _ in pairs(base_type_and_default) do
            table.insert(base_type_list, k)
        end
    end
    local r = math.random(1, #base_type_list)
    local t = base_type_list[r]
    return t, base_type_and_default[t]
end
local function getRandomPublic()
    local r = math.random(1,3)
    if r==1 then
        return "public"
    elseif r==2 then
        return "private"
    else
        return ""
    end
end

local property_info =
{
    p = "",
    name = "default",
    t = "int",
    v = "0",
}
function PropertyGenerate(p, n, t, v)
    local ta = setmetatable({},
        {
            __index = property_info,
        })

    ta.p = p or ta.p
    ta.name = n
    ta.t = t
    ta.v = v
    return ta
end

local attribute_info =
{
    p = "",
    name = "default",
    t = "int",
    property_info = nil,
}
function AttributeGenerate(p, n, t, pi)
    local ta = setmetatable({},
        {
            __index = attribute_info,
        })

    ta.p = p or ta.p
    ta.name = n
    ta.property_info = pi
    if pi~=nil then
        ta.t = pi.t
    end
    return ta
end

local method_info =
{
    p = "",

    name = "default",
    --[[
        {{"type1", "name1"}, {"type2", "name2"}, ..}
    ]]
    params = nil,
    --[[
        {"type", "value"}
    ]]
    retn = nil,

    content = nil,
}
function MethodContentGenerate(ci)

    content = {}

    local function getRandomP(t)
        return t[math.random(1, #t)]
    end

    for i=1, 10 do
        local t = getRandomType()
        local m = ci.typemap[t]
        local f = base_type_randomfunction[t]
        if #m > 0 then
            local a = getRandomP(m)
            local c = f(a, getRandomP(m),getRandomP(m))
            for _, v in ipairs(c) do
                table.insert(content, v)
            end
        end
    end

    return content
end

function MethodGenerate(ci, p, n, r)
    local ta = setmetatable({},
        {
            __index = method_info,
        })

    ta.p = p or ta.p
    ta.name = n
    ta.retn = r
    ta.content = MethodContentGenerate(ci)
    return ta
end

local class_info =
{
    p = "",
    name = "default",
    implement = nil,

    properties = nil,
    attributes = nil,

    typemap = nil,
}

local classes = {}

local classnames = {}
function GetNextClassName(min, max)
    local r = math.random(min or 10, max or 10)
    while true do
        local n = getRandomName(r)
        if classnames[n] == nil then
            classnames[n] = true
            return n
        end
    end
end

--[[
- 类生成函数
- 参数
	mc: 函数数量
	pc: 变量数量
	ac: 属性数量
]]
function ClassGenerater(mc, pc, ac)
    local class = setmetatable({},
        {
            __index = class_info,
        })

    local usedname = {}
    function GetNextName(min, max)
        local r = math.random(min or 10, max or 10)
        while true do
            local n = getRandomName(r)
            if usedname[n] == nil then
                usedname[n] = true
                return n
            end
        end
    end

    class.name = GetNextClassName(10, 40)
    usedname[class.name] = true;
    --class.implement = "MonoBehaviour"

    class.properties = {}
    for i=1, pc or 20 do
        table.insert(class.properties,
            PropertyGenerate(
                getRandomPublic(),
                GetNextName(10, 40),
                getRandomType()
            ))
    end

    class.attributes = {}
    for i=1, ac or 20 do
        local t, v = getRandomType()
        local pi = nil
        if math.random(10) < 3 then
            pi = class.properties[math.random(#class.properties)]
        end
        table.insert(class.attributes,
            AttributeGenerate(
                "public",
                GetNextName(10, 40),
                t, pi
            ))
    end

    class.typemap = {}
    for _, v in ipairs(base_type_list) do
        class.typemap[v] = {}
    end
    for _, v in ipairs(class.properties) do
        table.insert(class.typemap[v.t], v.name)
    end
    for _, v in ipairs(class.attributes) do
        table.insert(class.typemap[v.t], v.name)
    end

    class.methods = {}
    for i=1, mc or 20 do
        local t, v = getRandomType()
        local pi = nil
        if math.random(10) < 3 then
            pi = class.properties[math.random(#class.properties)]
        end
        table.insert(class.methods,
            MethodGenerate(class,
                "public",
                GetNextName(10, 40)
            ))
    end

    return class
end

function GetClassSource(class)

    local r = ""
    local t = 0
    local s = function(str)
        for i=1, t do
            r = r.."    "
        end
        r = r..str.."\r\n"
    end
    local _property = function(p)
        s(p.p .. " " .. p.t .. " " .. p.name .. " = " .. p.v .. ";")
    end
    local _attribute = function(a)
        s(a.p .. " " .. a.t .. " " .. a.name)
        s "{"
        t = t +1

        if a.property_info then
            local p = a.property_info
            s("get { return " .. p.name .. "; }")
            s("set { " .. p.name .. " = value; }")
        else
            s("get;")
            s("set;")
        end

        t = t -1
        s "}"
    end
    local _method = function(m)
        local ty = "void"
        if m.retn ~= nil then
            ty = m.retn[1]
        end
        local p = "()"
        if m.params ~= nil then
            p = ""
            for _, v in ipairs(m.params) do
                if string.len(p) > 0 then
                    p = p .. "," .. v[1] .. " " .. v[2]
                else
                    p = v[1] .. " " .. v[2]
                end
            end
            p = "(" .. p .. ")"
        end

        s(m.p.." ".. ty .." ".. m.name .. p)
        s"{"
        t = t+1

        for _, v in ipairs(m.content) do
            s(v)
        end
        t = t-1
        s"}"
    end

    s(class.p .. " class "..class.name..((class.implement~=nil and (" : "..class.implement)) or ""))
    s"{"
    t = t+1

    if class.properties ~= nil then
        for _, p in ipairs(class.properties) do
            _property(p)
        end
    end
    if class.attributes ~= nil then
        for _, p in ipairs(class.attributes) do
            _attribute(p)
        end
    end
    if class.methods ~= nil then
        for _, m in ipairs(class.methods) do
            _method(m)
        end
    end
    t = t-1
    s"}"

    return r
end

local function precent_bar(v, l)
    local p = {".", "-", "="}
    local pl = #p
    local line = ""
    local per = v
    local s = per*l
    local n = math.floor(s)
    local ns = math.floor((s - n) * pl)+1
    for i=1, l do
        if i<n+1 then
            line = line .. p[pl]
        elseif i==n+1 then
            line = line .. p[ns]
        else
            line = line .. p[1]
        end
    end
    return line
end

local help =
[[C# Garbage Code Generater
	-h: Help
	-o: Output Dir, Default="garbate"
	-c: Generate Class Count, Default=400
	-mc: Method Count, Default=30
	-pc: Property Count, Default=30
	-ac: Attribute Count, Default=30
	-verbose: Print Every Generate Class Name
	-q: QuietMode, Print Nothing
]]
function main()
    local name = "garbage"
    local class_count = 400
    local method_count = 30
    local property_count = 30
    local attribute_count = 30
    local verbose = false
    local quiet = false

    if arg then
        local len = #arg
        for i=1, len do
            local v = arg[i]
            if v == "--h" or v == "--H" or
                    v == "-h" or v == "-H" or v == "?" then
                print(help)
                return
            elseif (v == "-c" or v == "--c") and i < len then
                i = i+1
                class_count = 0 + arg[i]
            elseif (v == "-o" or v == "--o") and i < len then
                i = i+1
                name = arg[i]
            elseif (v == "-mc" or v == "--mc") and i < len then
                i = i+1
                method_count = 0 + arg[i]
            elseif (v == "-pc" or v == "--pc") and i < len then
                i = i+1
                property_count = 0 + arg[i]
            elseif (v == "-ac" or v == "--ac") and i < len then
                i = i+1
                attribute_count = 0 + arg[i]
            elseif v == "-verbose" then
                verbose = true
            elseif v == "-q" or v == "-quiet" then
                quiet = true
            end
        end
    end

    if not quiet then
        print("output = " .. name)
        print("class count = " .. class_count)
        print("method count = " .. method_count)
        print("property count = " .. property_count)
        print("attribute count = " .. attribute_count)
    end

    local path = name .. "/"
    pcall(function()
        os.execute("mkdir "..name)
    end)

    for i=1, class_count do
        local class = ClassGenerater(method_count, property_count, attribute_count)
        os.remove("test.cs")
        local f = io.open(path .. class.name .. ".cs", "wb")
        f:write(GetClassSource(class))
        f:close()

        if not quiet then
            if verbose then
                print(class.name .. ".cs")
            else
                io.write("\013".. "|"..precent_bar(i/class_count, 60) .. "| " .. string.format("%5d/%5d", i, class_count))
            end
        end
    end
    if not quiet then
        print("\nFin!")
    end
end

main()
  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
当你开始使用 Unity 开发游戏时,你需要学习 Unity 的基础知识,包括场景和对象的概念、使用 Inspector 来设置对象属性、使用组件来实现对象的功能、使用脚本来编写游戏逻辑等。此外,你还需要熟悉 Unity 的图形界面、资源管理、动画制作、物理模拟、音效制作等方面的功能。 下面是一个简单的动作游戏示例,代码示例中包括了玩家的移动、攻击和受伤等功能: ```csharp using UnityEngine; public class PlayerController : MonoBehaviour { public float speed = 10.0f; // 玩家移动速度 public float attackRange = 1.0f; // 攻击范围 public int attackPower = 10; // 攻击力 public int maxHealth = 100; // 最大生命值 private Rigidbody2D rigidbody2D; // 玩家刚体组件 private Animator animator; // 玩家动画组件 private int health; // 当前生命值 private void Start() { rigidbody2D = GetComponent<Rigidbody2D>(); animator = GetComponent<Animator>(); health = maxHealth; } private void Update() { // 玩家移动 float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector2 velocity = new Vector2(horizontal, vertical) * speed; rigidbody2D.velocity = velocity; // 玩家攻击 if (Input.GetKeyDown(KeyCode.Space)) { Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, attackRange); foreach (Collider2D collider in colliders) { if (collider.CompareTag("Enemy")) { EnemyController enemy = collider.GetComponent<EnemyController>(); enemy.TakeDamage(attackPower); } } } } public void TakeDamage(int damage) { health -= damage; if (health <= 0) { Die(); } else { animator.SetTrigger("hurt"); } } private void Die() { animator.SetTrigger("die"); Destroy(gameObject, 2.0f); } } ``` 以上代码示例包括了以下功能: 1. 玩家移动:通过获取输入的水平和垂直方向上的输入值,计算出玩家的速度,然后将速度设置给刚体组件,从而实现玩家的移动。 2. 玩家攻击:当玩家按下空格键时,通过 OverlapCircleAll 方法获取攻击范围内的所有碰撞体,然后遍历碰撞体,如果碰撞体的 Tag 是 Enemy,则获取 EnemyController 组件,并调用 TakeDamage 方法,从而实现攻击敌人的功能。 3. 玩家受伤和死亡:当玩家受到攻击时,通过调用 TakeDamage 方法减少生命值,如果生命值小于等于 0,则调用 Die 方法,播放死亡动画,并在 2 秒后销毁玩家对象。 当你编写完代码后,你还需要在 Unity 中创建场景、添加玩家和敌人等对象、将脚本组件添加到对象上,并设置对象的属性和动画等,从而实现完整的游戏功能。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林新发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值