微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

一、前言

点关注不迷路,持续输出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, 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 .. ") ",
            }
        elseif r == 5 then
            return {a .. " = " .. b .. " || " .. c ..";", }
        else
            return {a .. " = " .. b .. " && " .. c ..";", }
        end
    end,
    ["int"] = function(a, 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,
                c .. " = " .. math.random(1,
            }
        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, 6)
        if r==1 then
            return {a .. " = " .. b .. " + " .. c ..";", 10000) ..".0f;",
    ["double"] = function(a, 10000) ..".0;",
    ["string"] = function(a, 3)
        if r==1 then
            return {a .. " = " .. b .. " + " .. c ..";", }
        elseif r==2 then
            return {
                a .. " = string.Format("..c ..","..b..");",
}

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 = "",
    property_info = nil,
}
function AttributeGenerate(p, 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, 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 = "",
    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",
                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", 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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐