精华内容
下载资源
问答
  • 我的大学图书馆 Unity用自作ライブラリ(用于UnityC#) アイコン 命名空间: 班级: 结构: 枚举: 构成 R2357 算法 除错 扩展名 文字标记
  • ``` GameObject.find("Maintext").GetComponent().text="unityC#语代码更改Text,怎么才能首行缩进?\n"; ```
  • UnityC#解析嵌套json数据,json数组解析

    嵌套1:带有数组的解析:


    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;


    public class passportLoginData_serverInfo{
        public string subgane = "";
        public string serverName = "";//name
        public string hotDegree = "";
        public string roleInfoURL = "";
        public string state = "";
        public string serverIndex = "";
        public string onlineCount = "";//
        public string ip = "";
    }
    public class passportLoginData_areaInfo{

        public int serverCount = 1;//subgameCount
        public int areaIndex = 1;
        public string areaName = "";

    }
    public class passportLoginData_Channel{
        public string notice = "";
        public int areaCount = 0;//regionCount
        public string game = "";
        public string channel = "";
        public string passport = "";
        public string password = "";
        public string token = "";
        public string uid = "";
        public string needActive = "";
        public string lastLoginSubgame = "";
        public string channelVipLevel = "";//qq_vip
    }


    public static void parseJsonArray_passportLogin(){
            string jsonText = @"{
        ""code"": 0,
        ""message"": ""操作成功"",
        ""data"": {
            ""notice"": """",
            ""regionCount"": 1,
            ""regions"": [
                {
                    ""number"": 1,
                    ""name"": ""xxx1区"",
                    ""subgameCount"": 2,
                    ""subgames"": [
                        {
                            ""subgame"": 1001,
                            ""name"": ""xxx1区"",
                            ""hotDegree"": ""0"",
                            ""roleInfoURL"": ""http://10.0.0.38:10065/api/roleInfo.jhtml"",
                            ""state"": ""维护"",
                            ""entranceCount"": 1,
                            ""onlineCount"": ""-1"",
                            ""ip"": ""10.0.0.32:5089""
                        },{
                            ""subgame"": 1002,
                            ""name"": ""xxx21区"",
                            ""hotDegree"": ""20"",
                            ""roleInfoURL"": ""http://10.10.02.38:10065/api/roleInfo.jhtml"",
                            ""state"": ""12维护"",
                            ""entranceCount"": 11,
                            ""onlineCount"": ""-12"",
                            ""ip"": ""10.0.0.3:5089""
                        }
                    ]
                }
            ],
            ""game"": ""mmkr"",
            ""channel"": ""AGS130R"",
            ""passport"": ""8382dbaass992c53e76"",
            ""password"": """",
            ""token"": ""af67dedddd216c0b7"",
            ""nickname"": """",
            ""uid"": ""98887af0sdea8f81f6b5d"",
            ""needActive"": ""false"",
            ""isNew"": ""1"",
            ""lastLoginSubgame"": ""000000"",
            ""qq_vip"": ""0"",
            ""mail"": """"
        }
    }";  


            JObject msgData = (JObject)JsonConvert.DeserializeObject(jsonText); 
            string key = "code";
            if(msgData.Property (key)==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key); 
                return;
            }
            string code = msgData [key].ToString ();
            Debug.Log ("parseJsonArray_passportLogin(),code=="+code); 
            key = "message";
            if(msgData.Property (key)==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key); 
                return;
            }
            string message = msgData [key].ToString ();
            Debug.Log ("parseJsonArray_passportLogin(),message=="+message); 

            passportLoginData passportData = new passportLoginData ();
            passportData.code = code;
            passportData.message = message;

            passportLoginData_Channel loginInfo = new passportLoginData_Channel ();


            string key2 = "";
            key = "data";
            key2 = "notice";
            if(msgData.Property (key)==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key); 
                return;
            }
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string notice = msgData [key] [key2].ToString ();
            loginInfo.notice = notice;
            Debug.Log ("parseJsonArray_passportLogin(),notice=="+notice); 
            key2 = "regionCount";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string regionCount = msgData [key] [key2].ToString ();
            int.TryParse(regionCount,out loginInfo.areaCount) ;
            Debug.Log ("parseJsonArray_passportLogin(),regionCount=="+regionCount); 
            key2 = "game";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string game = msgData [key] [key2].ToString ();
            loginInfo.game = game;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.game=="+loginInfo.game);
            key2 = "channel";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string channel = msgData [key] [key2].ToString ();
            loginInfo.channel = channel;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.channel=="+loginInfo.channel);
            key2 = "passport";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string passport = msgData [key] [key2].ToString ();
            loginInfo.passport = passport;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.passport=="+loginInfo.passport);
            key2 = "token";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string token = msgData [key] [key2].ToString ();
            loginInfo.token = token;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.token=="+loginInfo.token);
            key2 = "password";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string password = msgData [key] [key2].ToString ();
            loginInfo.password = password;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.password=="+loginInfo.password);
            key2 = "uid";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string uid = msgData [key] [key2].ToString ();
            loginInfo.uid = uid;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.uid=="+loginInfo.uid);
            key2 = "needActive";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string needActive = msgData [key] [key2].ToString ();
            loginInfo.needActive = needActive;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.needActive=="+loginInfo.needActive);
            key2 = "lastLoginSubgame";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string lastLoginSubgame = msgData [key] [key2].ToString ();
            loginInfo.lastLoginSubgame = lastLoginSubgame;
            Debug.Log ("parseJsonArray_passportLogin(),loginInfo.lastLoginSubgame=="+loginInfo.lastLoginSubgame);


            key2 = "regions";
            if(msgData [key] [key2]==null ){
                Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2); 
                return;
            }
            string key3 = "";

            int realAreaCount = 0;
            foreach (JToken tok in msgData [key] [key2])//遍历数组
            {
                realAreaCount++;
            }

            passportLoginData_areaInfo[] areaArray = new passportLoginData_areaInfo[loginInfo.areaCount];

            for(int i = 0;i<loginInfo.areaCount;i++){//多个区
                //JToken regionData= msgData[key][key2][i];

                if(i>=realAreaCount){
                    Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",error:realAreaCount=="+realAreaCount); 
                    continue;
                }


                areaArray[i] = new passportLoginData_areaInfo();
                if(msgData [key] [key2][i]==null ){
                    Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i); 
                    continue;
                }

                string regionsJsonStr = msgData[key][key2][i].ToString();
                JObject regionData = (JObject)JsonConvert.DeserializeObject(regionsJsonStr); 
                key3 = "number";
                if(regionData.Property (key3) == null){
                    Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3);
                    continue;
                }
                areaArray [i].areaIndex = (int)regionData [key3];
                Debug.Log ("parseJsonArray_passportLogin(),areaI=="+i+",areaArray [i].areaIndex=="+areaArray [i].areaIndex);
                key3 = "name";
                if(regionData.Property (key3) == null){
                    Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3);
                    continue;
                }
                areaArray [i].areaName = regionData [key3].ToString ();
                Debug.Log ("parseJsonArray_passportLogin(),areaI=="+i+",areaArray [i].areaName=="+areaArray [i].areaName);

                key3 = "subgameCount";
                if(regionData.Property (key3) == null){
                    Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3);
                    continue;
                }
                string subgameCount = regionData [key3].ToString ();
                int.TryParse (subgameCount,out areaArray [i].serverCount);
                Debug.Log ("parseJsonArray_passportLogin(),areaI=="+i+",areaArray [i].serverCount=="+areaArray [i].serverCount);
                key3 = "subgames";
                if(regionData.Property (key3) == null){
                    Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3);
                    continue;
                }

                int realServerCount = 0;
                foreach (JToken baseJ in regionData[key3])//遍历数组
                {
                    realServerCount++;
                }
                Debug.Log ("parseJsonArray_passportLogin(),areaI=="+i+",realServerCount=="+realServerCount);

                passportLoginData_serverInfo[] serverArray = new passportLoginData_serverInfo[areaArray [i].serverCount];
                for(int j=0;j<areaArray[i].serverCount;j++){
     
                    Debug.Log ("parseJsonArray_passportLogin(),11111,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",j=="+j); 
                    serverArray [j] = new passportLoginData_serverInfo ();

                    Debug.Log ("parseJsonArray_passportLogin(),22222,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",j=="+j); 

                    if(j >= realServerCount){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",j=="+j+",error:realServerCount=="+realServerCount); 
                        continue;
                    }


                    if(regionData[key3][j]==null ){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",j=="+j); 
                        continue;
                    }
                    Debug.Log ("parseJsonArray_passportLogin(),33333,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",j=="+j); 
                    string serverJsonStr = regionData[key3][j].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),areaI=="+i+",serverJ=="+j+",serverJsonStr=="+serverJsonStr);

                    JObject serverData = (JObject)JsonConvert.DeserializeObject(serverJsonStr);
                    string key4 = "subgame";
                    if(serverData.Property (key4) == null){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",key4=="+key4);
                        continue;
                    }
                    serverArray[j].subgane = serverData[key4].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),serverJ=="+j+",serverArray[j].subgane=="+serverArray[j].subgane);
                    key4 = "name";
                    if(serverData.Property (key4) == null){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",key4=="+key4);
                        continue;
                    }
                    serverArray[j].serverName = serverData[key4].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),serverJ=="+j+",serverArray[j].serverName=="+serverArray[j].serverName);

                    key4 = "hotDegree";
                    if(serverData.Property (key4) == null){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",key4=="+key4);
                        continue;
                    }
                    serverArray[j].hotDegree = serverData[key4].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),serverJ=="+j+",serverArray[j].hotDegree=="+serverArray[j].hotDegree);

                    key4 = "state";
                    if(serverData.Property (key4) == null){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",key4=="+key4);
                        continue;
                    }
                    serverArray[j].state = serverData[key4].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),serverJ=="+j+",serverArray[j].state=="+serverArray[j].state);

                    key4 = "ip";
                    if(serverData.Property (key4) == null){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",key4=="+key4);
                        continue;
                    }
                    serverArray[j].ip = serverData[key4].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),serverJ=="+j+",serverArray[j].ip=="+serverArray[j].ip);

                    key4 = "entranceCount";
                    if(serverData.Property (key4) == null){
                        Debug.Log ("parseJsonArray_passportLogin(),keyNotExist,key=="+key+",key2=="+key2+",i=="+i+",key3=="+key3+",key4=="+key4);
                        continue;
                    }
                    serverArray[j].serverIndex = serverData[key4].ToString();
                    Debug.Log ("parseJsonArray_passportLogin(),serverJ=="+j+",serverArray[j].serverIndex=="+serverArray[j].serverIndex);

                }
            }
        }




    嵌套2:不含数组

    {

        "500": {
            "payChannel": "google",
            "updateurl": "10.0.0.38",
            "passporturl": "passport.xxx.com",
            "loginInterface": "/xxx/sdk/login",
            "chargeinfo": {
                "7777": "xr300krwzs",
                "777": "xm500krwzs",
                "888": "xmr.kr.11000krwzs",
                "555": "xmr.kr.33000krwzs",
                "999": "xs",
                "456": "",
                "345": "xmr.kr.33000krwcz",
                "chargeInterface": "/google/pay"
            }
        },
        "describe": "the first Key is AppId code"

    }


    代码:

    string key = "500";

            JObject msgData = (JObject)JsonConvert.DeserializeObject(jsonStr);
            LogView.setViewText ("GameGlobal.cs,setChannelInfo(),msgData.Count=="+msgData.Count);
            string channelStr = msgData.Property (key)!=null ? msgData[key].ToString() : "error_noKey";
            //LogView.setViewText ("GameGlobal.cs,setChannelInfo(),channelStr=="+channelStr);
            if(channelStr=="error_noKey"){
                LogView.setViewText ("GameGlobal.cs,setChannelInfo(),error:channelStr==error_noKey");
                return;
            }

            JObject itemData = (JObject)JsonConvert.DeserializeObject(channelStr);

            key = "payChannel";
            string payChannel = itemData.Property (key)!=null ? itemData[key].ToString() : "error_noKey";
            key = "updateurl";
            string updateurl = itemData.Property (key)!=null ? itemData[key].ToString() : "error_noKey";
            key = "passporturl";
            string passporturl = itemData.Property (key)!=null ? itemData[key].ToString() : "error_noKey";
            key = "loginInterface";
            string loginInterface = itemData.Property (key)!=null ? itemData[key].ToString() : "error_noKey";
            key = "chargeinfo";
            string chargeInfoJsonStr = itemData.Property (key)!=null ? itemData[key].ToString() : "error_noKey";
            JObject chargeData = (JObject)JsonConvert.DeserializeObject(chargeInfoJsonStr);

    展开全文
  • UnityC#编码规范

    2019-02-26 15:39:50
    (1)统一规范,方便阅读、维护,提高代码质量。 (2)统一格式,使代码度量、工作量评估更加精确。为公司软件过程体系优化打好基础。
  • UnityC#调用so文件

    2019-11-23 17:09:35
    文章目录1.so源文件1.1 NaviteCode.h1.2 ...Unity中C#调用so文件中返回字符串。 1.so源文件 1.1 NaviteCode.h #ifndef __NativeCode_H__ #define __NativeCode_H__ #if 0 #define EXPORT_DLL __declspe...


    Unity中C#调用so文件中返回字符串。

    1.so源文件

    1.1 NaviteCode.h

        #ifndef __NativeCode_H__
        #define __NativeCode_H__
    
        #if 0
        #define EXPORT_DLL __declspec(dllexport) //导出dll声明
        #else
        #define EXPORT_DLL 
        #endif
    
        extern "C" {
            EXPORT_DLL int MyAddFunc(int _a, int _b);
    		EXPORT_DLL char* GetAppKey();
        }
    
        #endif
    
    

    1.2 NaviteCode.cpp

        #include "NaviteCode.h"
        #include <cstring>
        using namespace std;
    
        extern "C" {
            int MyAddFunc(int _a, int _b)
            {
                return _a + _b;
            }
    
            // static char* key = "aShLdS$u3p@V-btd5dKmQZdwa";
    		
            char buff[255]; 
            char* GetAppKey()
            {
                strcpy(buff,"aShLdS$u3p@V-btd5dKmQZdwa");
                return buff;
    		    //return "aShLdS$u3p@V-btd5dKmQZdwa";
            }
    
    }
    

    2.调用方法

    将上述生成的so文件放在Plugins-Android下

    using System;
    using System.Runtime.InteropServices;
    
    public class Jni
    {
        [DllImport("NativeCode")]
        public static extern IntPtr GetAppKey();
    }
    
    public class Usage
    {
        private string GetAppKey()
        {
            IntPtr keyPtr = Jni.GetAppKey();
            string appKey = Marshal.PtrToStringAnsi(keyPtr);
            Debug.Log("Login result:Get appKey " + appKey);
    
            return appKey;
        }
    }
    
    
    展开全文
  • 个人制作,精简实现unity客户端与远程server实时音视频交互,服务器加客户端总共只用了4个C#代码文件
  • unityC#基础代码

    2019-10-24 16:43:17
    unityc#基础 1.脚本作为行为组件 using UnityEngine ; using System . Collections ; public class ExampleBehaviourScript : MonoBehaviour { void Update ( ) { if ( Input . ...

    unityc#基础

    1.脚本作为行为组件

    using UnityEngine;
    using System.Collections;
    
    public class ExampleBehaviourScript : MonoBehaviour
    {
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.R))  //R键被按下
            {
                GetComponent<Renderer> ().material.color = Color.red;//颜色变为红色
            }
            if (Input.GetKeyDown(KeyCode.G))
            {
                GetComponent<Renderer>().material.color = Color.green;
            }
            if (Input.GetKeyDown(KeyCode.B))
            {
                GetComponent<Renderer>().material.color = Color.blue;
            }
        }
    }

    2.变量和函数

    using UnityEngine;
    using System.Collections;
    
    public class VariablesAndFunctions : MonoBehaviour
    {   
        int myInt = 5;
        
        
        void Start ()
        {
            myInt = MultiplyByTwo(myInt); //调用函数
            Debug.Log (myInt);
        }
        
        
        int MultiplyByTwo (int number)
        {
            int ret;
            ret = number * 2;
            return ret;
        }
    }

    3.惯例与句法

    using UnityEngine;
    using System.Collections;
    
    public class BasicSyntax : MonoBehaviour
    {
        void Start ()
        {
            Debug.Log(transform.position.x);
            
            if(transform.position.y <= 5f)
            {
                Debug.Log ("I'm about to hit the ground!");
            }
        }
    }

    4.if语句

    using UnityEngine;
    using System.Collections;
    
    public class IfStatements : MonoBehaviour
    {
        float coffeeTemperature = 85.0f;
        float hotLimitTemperature = 70.0f;
        float coldLimitTemperature = 40.0f;
        
    
        void Update ()
        {
            if(Input.GetKeyDown(KeyCode.Space))
                TemperatureTest();
            
            coffeeTemperature -= Time.deltaTime * 5f;
        }
        
        
        void TemperatureTest ()
        {
            // If the coffee's temperature is greater than the hottest drinking temperature...
            if(coffeeTemperature > hotLimitTemperature)
            {
                // ... do this.
                print("Coffee is too hot.");
            }
            // If it isn't, but the coffee temperature is less than the coldest drinking temperature...
            else if(coffeeTemperature < coldLimitTemperature)
            {
                // ... do this.
                print("Coffee is too cold.");
            }
            // If it is neither of those then...
            else
            {
                // ... do this.
                print("Coffee is just right.");
            }
        }
    }

    5.循环语句

    for循环

    using UnityEngine;
    using System.Collections;
    
    public class ForLoop : MonoBehaviour
    {
        int numEnemies = 3;
        
        
        void Start ()
        {
            for(int i = 0; i < numEnemies; i++)
            {
                Debug.Log("Creating enemy number: " + i);
            }
        }
    }

    while循环

    using UnityEngine;
    using System.Collections;
    
    public class WhileLoop : MonoBehaviour
    {
        int cupsInTheSink = 4;
        
        
        void Start ()
        {
            while(cupsInTheSink > 0)
            {
                Debug.Log ("I've washed a cup!");
                cupsInTheSink--;
            }
        }
    }

    dowhile循环

    using UnityEngine;
    using System.Collections;
    
    public class DoWhileLoop : MonoBehaviour 
    {
        void Start()
        {
            bool shouldContinue = false;
            
            do
            {
                print ("Hello World");
                
            }while(shouldContinue == true);
        }
    }

    foreach循环

    using UnityEngine;
    using System.Collections;
    
    public class ForeachLoop : MonoBehaviour 
    {   
        void Start () 
        {
            string[] strings = new string[3];
            
            strings[0] = "First string";
            strings[1] = "Second string";
            strings[2] = "Third string";
            
            foreach(string item in strings)
            {
                print (item);
            }
        }
    }

    6.Awake and Strart

    using UnityEngine;
    using System.Collections;
    
    public class AwakeAndStart : MonoBehaviour
    {
        void Awake ()
        {
            Debug.Log("Awake called.");
        }
        
        
        void Start ()
        {
            Debug.Log("Start called.");
        }
    }

    7.Update and FixedUpdate

    using UnityEngine;
    using System.Collections;
    
    public class UpdateAndFixedUpdate : MonoBehaviour
    {
        void FixedUpdate ()
        {
            Debug.Log("FixedUpdate time :" + Time.deltaTime);
        }
        
        
        void Update ()
        {
            Debug.Log("Update time :" + Time.deltaTime);
        }
    }

    8.Scope and Access Modifiers

    ScopeAndAccessModifiers

    using UnityEngine;
    using System.Collections;
    
    public class ScopeAndAccessModifiers : MonoBehaviour
    {
        public int alpha = 5;
        
        
        private int beta = 0;
        private int gamma = 5;
        
        
        private AnotherClass myOtherClass;
        
        
        void Start ()
        {
            alpha = 29;
            
            myOtherClass = new AnotherClass();
            myOtherClass.FruitMachine(alpha, myOtherClass.apples);
        }
        
        
        void Example (int pens, int crayons)
        {
            int answer;
            answer = pens * crayons * alpha;
            Debug.Log(answer);
        }
        
        
        void Update ()
        {
            Debug.Log("Alpha is set to: " + alpha);
        }
    }

    AnotherClass

    using UnityEngine;
    using System.Collections;
    
    public class AnotherClass
    {
        public int apples;
        public int bananas;
        
        
        private int stapler;
        private int sellotape;
        
        
        public void FruitMachine (int a, int b)
        {
            int answer;
            answer = a + b;
            Debug.Log("Fruit total: " + answer);
        }
        
        
        private void OfficeSort (int a, int b)
        {
            int answer;
            answer = a + b;
            Debug.Log("Office Supplies total: " + answer);
        }
    }

    9.启用和禁用组件

    using UnityEngine;
    using System.Collections;
    
    public class EnableComponents : MonoBehaviour
    {
        private Light myLight;
        
        
        void Start ()
        {
            myLight = GetComponent<Light>();
        }
        
        
        void Update ()
        {
            if(Input.GetKeyUp(KeyCode.Space))
            {
                myLight.enabled = !myLight.enabled;
            }
        }
    }

    10.平移和旋转`

    using UnityEngine;
    using System.Collections;
    
    public class TransformFunctions : MonoBehaviour
    {
        public float moveSpeed = 10f;
        public float turnSpeed = 50f;
        
        
        void Update ()
        {
            if(Input.GetKey(KeyCode.UpArrow))
                transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
            
            if(Input.GetKey(KeyCode.DownArrow))
                transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
            
            if(Input.GetKey(KeyCode.LeftArrow))
                transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
            
            if(Input.GetKey(KeyCode.RightArrow))
                transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
        }
    }

    11.激活游戏对象

    ActiveObjects

    using UnityEngine;
    using System.Collections;
    
    public class ActiveObjects : MonoBehaviour
    {
        void Start ()
        {
            gameObject.SetActive(false);
        }
    }

    CheckState

    using UnityEngine;
    using System.Collections;
    
    public class CheckState : MonoBehaviour
    {
        public GameObject myObject;
        
        
        void Start ()
        {
            Debug.Log("Active Self: " + myObject.activeSelf);
            Debug.Log("Active in Hierarchy" + myObject.activeInHierarchy);
        }
    }

    12.Look At

    CameraLookat

    using UnityEngine;
    using System.Collections;
    
    public class CameraLookAt : MonoBehaviour
    {
        public Transform target;
        
        void Update ()
        {
            transform.LookAt(target);
        }
    }

    13.Destroy

    DestroyBasic

    using UnityEngine;
    using System.Collections;
    
    public class DestroyBasic : MonoBehaviour
    {
        void Update ()
        {
            if(Input.GetKey(KeyCode.Space))
            {
                Destroy(gameObject);
            }
        }
    }

    DestroyOther

    using UnityEngine;
    using System.Collections;
    
    public class DestroyOther : MonoBehaviour
    {
        public GameObject other;
        
        
        void Update ()
        {
            if(Input.GetKey(KeyCode.Space))
            {
                Destroy(other);
            }
        }
    }

    DestroyComponent

    using UnityEngine;
    using System.Collections;
    
    public class DestroyComponent : MonoBehaviour
    {
        void Update ()
        {
            if(Input.GetKey(KeyCode.Space))
            {
                Destroy(GetComponent<MeshRenderer>());
            }
        }
    }

    14.线性插值
    在进行游戏时,有时可以在两个值之间进行线性插值。这是通过一个名为Lerp的函数完成的。线性插值是指在两个给定的值之间找到一个一定百分比的值。例如,我们可以在数字3和5之间进行线性插值,得到数字4,这是因为4是介于3和5之间的50%。

    在联合中,有几个LERP函数可以用于不同的类型。对于我们刚才使用的例子,等效的是Mathf.Lerp函数,如下所示:

    // In this case, result = 4
    float result = Mathf.Lerp (3f, 5f, 0.5f);

    Lerp函数接受3个浮动参数:一个表示要插值的值,另一个表示要插值的值,最后一个浮点数表示插值的距离。在这种情况下,插值值为0.5,即50%。如果为0,则该函数将返回“FROM”值,如果为1时,该函数将返回“to”值。

    Lerp函数的其他示例包括Col.Lerp和Vector3.Lerp。这些工作方式与Mathf.Lerp完全相同,但“From”和“to”值分别为Color和Vector 3类型。在每种情况下,第三个参数仍然是一个浮点数,表示要插值多少。这些函数的结果是找到一个颜色,它是两个给定颜色的混合,一个向量,是两个给定向量之间的某个百分比。

    让我们看另一个例子:

    Vector3 from = new Vector3 (1f, 2f, 3f);
    Vector3 to = new Vector3 (5f, 6f, 7f);

    // Here result = (4, 5, 6)
    Vector3 result = Vector3.Lerp (from, to, 0.75f);

    在这种情况下,结果是(4,5,6),因为4是1到5之间的75%,5是2到6之间的75%,6是3到7之间的75%。

    在使用Col.Lerp时也应用了相同的原理。在颜色结构中,颜色由代表红色、蓝色、绿色和α的4个浮标表示。当使用LERP时,这些浮点数就像Mathf.Lerp和Vector3.Lerp一样被内插。

    在某些情况下,Lerp函数可以用来平滑随时间变化的值。考虑以下代码:

    void Update ()
    {
        light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f);
    }

    如果光的强度从0开始,那么在第一次更新之后,它将被设置为4。下一帧将设置为6,然后设置为7,然后设置为7.5等等。因此,在几个帧,灯光强度将倾向于8,但其变化速度将放缓,因为它接近它的目标。注意,这发生在几个帧的过程中。如果我们希望它不依赖于帧速率,那么我们可以使用以下代码:

    voidUpdate(){light.强度= Mathf.Lerp(光强,8f,0.5F * Time.deltaTime); }

    void Update ()
    {
    light.intensity = Mathf.Lerp(light.intensity, 8f, 0.5f * Time.deltaTime);
    }
    强度的变化将发生在每秒而不是每帧。

    请注意,当平滑一个值时,通常最好使用SmoothDamp函数。只有当你确信你想要的效果时,才使用LERP来平滑。

    15.GetButton and GetKey

    KeyInput

    using UnityEngine;
    using System.Collections;
    
    public class KeyInput : MonoBehaviour
    {
        public GUITexture graphic;
        public Texture2D standard;
        public Texture2D downgfx;
        public Texture2D upgfx;
        public Texture2D heldgfx;
        
        void Start()
        {
            graphic.texture = standard;
        }
        
        void Update ()
        {
            bool down = Input.GetKeyDown(KeyCode.Space);
            bool held = Input.GetKey(KeyCode.Space);
            bool up = Input.GetKeyUp(KeyCode.Space);
            
            if(down)
            {
                graphic.texture = downgfx;
            }
            else if(held)
            {
                graphic.texture = heldgfx;
            }
            else if(up)
            {
                graphic.texture = upgfx;
            }
            else
            {
                graphic.texture = standard; 
            }
            
            guiText.text = " " + down + "\n " + held + "\n " + up;
        }
    }

    ButtonInput

    using UnityEngine;
    using System.Collections;
    
    public class ButtonInput : MonoBehaviour
    {
        public GUITexture graphic;
        public Texture2D standard;
        public Texture2D downgfx;
        public Texture2D upgfx;
        public Texture2D heldgfx;
        
        void Start()
        {
            graphic.texture = standard;
        }
        
        void Update ()
        {
            bool down = Input.GetButtonDown("Jump");
            bool held = Input.GetButton("Jump");
            bool up = Input.GetButtonUp("Jump");
            
            if(down)
            {
                graphic.texture = downgfx;
            }
            else if(held)
            {
                graphic.texture = heldgfx;
            }
            else if(up)
            {
                graphic.texture = upgfx;
            }
            else
            {
                graphic.texture = standard;
            }
        
            guiText.text = " " + down + "\n " + held + "\n " + up;
        }
    }

    16.GetComponent

    UsingOtherComponents

    using UnityEngine;
    using System.Collections;
    
    public class UsingOtherComponents : MonoBehaviour
    {
        public GameObject otherGameObject;
        
        
        private AnotherScript anotherScript;
        private YetAnotherScript yetAnotherScript;
        private BoxCollider boxCol;
        
        
        void Awake ()
        {
            anotherScript = GetComponent<AnotherScript>();
            yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
            boxCol = otherGameObject.GetComponent<BoxCollider>();
        }
        
        
        void Start ()
        {
            boxCol.size = new Vector3(3,3,3);
            Debug.Log("The player's score is " + anotherScript.playerScore);
            Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
        }
    }

    AnotherScript

    using UnityEngine;
    using System.Collections;
    
    public class AnotherScript : MonoBehaviour
    {
        public int playerScore = 9001;
    }

    YetAnotherScript

    using UnityEngine;
    using System.Collections;
    
    public class YetAnotherScript : MonoBehaviour
    {
        public int numberOfPlayerDeaths = 3;
    }

    17.OnMouseDown
    MouseClick

    using UnityEngine;
    using System.Collections;
    
    public class MouseClick : MonoBehaviour
    {
        void OnMouseDown ()
        {
            rigidbody.AddForce(-transform.forward * 500f);
            rigidbody.useGravity = true;
        }
    }
    
    

    18.GetAxis

    AxisExample

    using UnityEngine;
    using System.Collections;
    
    public class AxisExample : MonoBehaviour
    {
        public float range;
        public GUIText textOutput;
        
        
        void Update () 
        {
            float h = Input.GetAxis("Horizontal");
            float xPos = h * range;
            
            transform.position = new Vector3(xPos, 2f, 0);
            textOutput.text = "Value Returned: "+h.ToString("F2");  
        }
    }

    AxisRawExample

    using UnityEngine;
    using System.Collections;
    
    public class AxisRawExample : MonoBehaviour
    {
        public float range;
        public GUIText textOutput;
        
        
        void Update () 
        {
            float h = Input.GetAxisRaw("Horizontal");
            float xPos = h * range;
            
            transform.position = new Vector3(xPos, 2f, 0);
            textOutput.text = "Value Returned: "+h.ToString("F2");  
        }
    }
    
    

    DualAxisExample

    using UnityEngine;
    using System.Collections;
    
    public class DualAxisExample : MonoBehaviour 
    {
        public float range;
        public GUIText textOutput;
        
        
        void Update () 
        {
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");
            float xPos = h * range;
            float yPos = v * range;
            
            transform.position = new Vector3(xPos, yPos, 0);
            textOutput.text = "Horizontal Value Returned: "+h.ToString("F2")+"\nVertical Value Returned: "+v.ToString("F2");    
        }
    }

    19.DeltaTime

    using UnityEngine;
    using System.Collections;
    
    public class UsingDeltaTime : MonoBehaviour
    {
        public float speed = 8f; 
        public float countdown = 3.0f;
    
        
        void Update ()
        {
            countdown -= Time.deltaTime;
            if(countdown <= 0.0f)
                light.enabled = true;
            
             if(Input.GetKey(KeyCode.RightArrow))
                transform.position += new Vector3(speed * Time.deltaTime, 0.0f, 0.0f);
        }   
    }

    20.Classes

    SingleCharacterScript

    using UnityEngine;
    using System.Collections;
    
    public class SingleCharacterScript : MonoBehaviour
    {
        public class Stuff
        {
            public int bullets;
            public int grenades;
            public int rockets;
            
            public Stuff(int bul, int gre, int roc)
            {
                bullets = bul;
                grenades = gre;
                rockets = roc;
            }
        }
        
        
        public Stuff myStuff = new Stuff(10, 7, 25);
        public float speed;
        public float turnSpeed;
        public Rigidbody bulletPrefab;
        public Transform firePosition;
        public float bulletSpeed;
        
        
        void Update ()
        {
            Movement();
            Shoot();
        }
        
        
        void Movement ()
        {
            float forwardMovement = Input.GetAxis("Vertical") * speed * Time.deltaTime;
            float turnMovement = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
            
            transform.Translate(Vector3.forward * forwardMovement);
            transform.Rotate(Vector3.up * turnMovement);
        }
        
        
        void Shoot ()
        {
            if(Input.GetButtonDown("Fire1") && myStuff.bullets > 0)
            {
                Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;
                bulletInstance.AddForce(firePosition.forward * bulletSpeed);
                myStuff.bullets--;
            }
        }
    }
    

    Inventory

    using UnityEngine;
    using System.Collections;
    
    public class Inventory : MonoBehaviour
    {
        public class Stuff
        {
            public int bullets;
            public int grenades;
            public int rockets;
            public float fuel;
            
            public Stuff(int bul, int gre, int roc)
            {
                bullets = bul;
                grenades = gre;
                rockets = roc;
            }
            
            public Stuff(int bul, float fu)
            {
                bullets = bul;
                fuel = fu;
            }
            
            // Constructor
            public Stuff ()
            {
                bullets = 1;
                grenades = 1;
                rockets = 1;
            }
        }
        // Creating an Instance (an Object) of the Stuff class
        public Stuff myStuff = new Stuff(50, 5, 5);
        
        public Stuff myOtherStuff = new Stuff(50, 1.5f);
        
        void Start()
        {
            Debug.Log(myStuff.bullets); 
        }
    }

    MovementControls

    using UnityEngine;
    using System.Collections;
    
    public class MovementControls : MonoBehaviour
    {
        public float speed;
        public float turnSpeed;
        
        
        void Update ()
        {
            Movement();
        }
        
        
        void Movement ()
        {
            float forwardMovement = Input.GetAxis("Vertical") * speed * Time.deltaTime;
            float turnMovement = Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime;
            
            transform.Translate(Vector3.forward * forwardMovement);
            transform.Rotate(Vector3.up * turnMovement);
        }
    }

    Shooting

    using UnityEngine;
    using System.Collections;
    
    public class Shooting : MonoBehaviour
    {
        public Rigidbody bulletPrefab;
        public Transform firePosition;
        public float bulletSpeed;
        
        
        private Inventory inventory;
        
        
        void Awake ()
        {
            inventory = GetComponent<Inventory>();
        }
        
        
        void Update ()
        {
            Shoot();
        }
        
        
        void Shoot ()
        {
            if(Input.GetButtonDown("Fire1") && inventory.myStuff.bullets > 0)
            {
                Rigidbody bulletInstance = Instantiate(bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;
                bulletInstance.AddForce(firePosition.forward * bulletSpeed);
                inventory.myStuff.bullets--;
            }
        }
    }
    展开全文

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,912
精华内容 1,564
关键字:

unityc#

c# 订阅