Unity 初学记录

简介: Unity 初学记录

1.点击检测:(射线检测)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class click : MonoBehaviour {
    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
private RaycastHit ObjHit;
    private Ray CustomRay;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
#if UNITY_ANDROID || UNITY_IPHONE
            //移动端判断如下
            if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
            //PC端判断如下
            if (EventSystem.current.IsPointerOverGameObject())
#endif
            {
                Debug.Log("当前点击在UI上" + EventSystem.current.currentSelectedGameObject);
            }
            else
            {
              //从摄像机发出一条射线,到点击的坐标
                CustomRay = Camera.main.ScreenPointToRay(Input.mousePosition);
                //显示一条射线,只有在scene视图中才能看到
                Debug.DrawLine(CustomRay.origin, ObjHit.point, Color.red, 2);
                if (Physics.Raycast(CustomRay, out ObjHit, 100))
                {
                    if (ObjHit.collider.gameObject != null)
                    {
                        Debug.Log("Click Object:" + ObjHit.collider.gameObject);
                    }
                }
                else
                {
                    Debug.Log("Click Null");
                }
            }
        }
    }
}

2.按键检测:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Score : MonoBehaviour {
    public static Text txt;                //定义静态变量名以用于其他脚本内的引用**
    public static Text txxt;
    public static float x = 0;
    public static float MaxScore=999999999999;//分数上限
    // Use this for initialization
    void Start () {
        Cursor.lockState = CursorLockMode.None;
        txt = GameObject.Find("积分").GetComponent<Text>();
        txxt = GameObject.Find("最高分").GetComponent<Text>();
    }   
        private void KeyControl(){
            int w=0,s=0,a=0,d=0,sp=0;
        if (Input.GetKeyDown (KeyCode.W))
        {
            w += 1;
            Debug.Log("你向前走了");
        }
        if (Input.GetKeyDown (KeyCode.S))
        {
            s += 1;
            Debug.Log("你向后走了");
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            a += 1;
            Debug.Log("你向左走了");
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            d += 1;
            Debug.Log("你向右走了");
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            sp += 1;
            Debug.Log("你跳起来了");
        }
    }
    // Update is called once per frame
    void Update () {
        Cursor.lockState = CursorLockMode.None;//鼠标解锁并显示
        if (x < MaxScore)
        {
            x++;
            Score.txt.text = "积分:" + x.ToString();
            if (x > Convert.ToInt32(Score.txxt.text)) ;
            {
                //Score.txxt.text =  x.ToString();
            }
        }
        else
        {
            Score.txt.text = "积分:"+ x.ToString()+" 积分已满";
        }
        //Control();
        KeyControl();
    }
}

3.场景切换

using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
[RequireComponent(typeof (GUITexture))]
public class ForcedReset : MonoBehaviour
{
    private void Update()
    {
        // if we have forced a reset ...
        if (CrossPlatformInputManager.GetButtonDown("ResetObject"))
        {
            //... reload the scene
            SceneManager.LoadScene(SceneManager.GetSceneAt(0).name);
        }
    }
}

4.登录界面

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using UnityEngine.SceneManagement;
public class log : MonoBehaviour
{
    //private SqlConnection conn;
    //private string con = "Server=DESKTOP-D2ERGMG\\SQLEXPRESS;integrated security=SSPI; DataBase=unity;";
    private string userName;
    private string passWord;
    private string username;
    private string password;
    private string message;
    private string info;
    public Texture img;
    void OnGUI()
    {
        GUIStyle sty = new GUIStyle();
        GUIStyle sty1 = new GUIStyle();
        sty.fontSize = 20;
        sty1.fontSize = 40;
        GUI.Label(new Rect(120, 10, 100, 30), "登录界面", sty1);
        GUI.Label(new Rect(30, 70, 100, 30), "用户名:", sty);
        userName = GUI.TextField(new Rect(120, 70, 200, 30), userName, 20);
        GUI.Label(new Rect(30, 110, 100, 30), "密码:", sty);
        passWord = GUI.PasswordField(new Rect(120, 110, 200, 30), passWord, '*', 15);
        message = GUI.TextArea(new Rect(400, 30, 200, 200), message, sty);
        if (GUI.Button(new Rect(220, 150, 110, 30), "login"))
        {
        //string sqltest = "select * from user where userName ='" + userName + "'";
        try
        {
            //conn.Open();
            //SqlCommand sqlcom1 = new SqlCommand(sqltest, conn);
            //SqlDataReader read = sqlcom1.ExecuteReader();
            //read.Read();
            //if (read.HasRows && passWord == read["password"].ToString().Trim())
            if(password ==passWord &&username ==userName)
            {
                info = "success!";
                message = "登录成功\n";
                SceneManager.LoadScene("Underwater_FX");
            }
            else
                info = "failed!";
        }
        catch (System.Exception)
        {
            message = "登录失败\n";
            throw;
        }
        }
        sty.fontSize = 40;
        GUI.Label(new Rect(150, 210, 512, 225), info, sty);
    }
    // Use this for initialization
    void Start()
    {
        //conn = new SqlConnection(con);
        userName = "";
        passWord = "";
        message = "";
        info = "";
        username = "abc";
        password = "123";
    }
    // Update is called once per frame
    void Update()
    {
    }
}

5.数据存档

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.UI;
public class game : MonoBehaviour {
    public int score = 0;
    public static int sc=0;
    [SerializeField]   //可序列化
    private Text scoreText;
    void  Start()
    {
        Cursor.lockState =CursorLockMode.Confined ;
    }
    public static void getscore(int s)  //获取积分
    {
        sc = s;
    }
    public void SaveGame()              //存档
    {
        Debug.Log("Game Saved"+sc.ToString ()+' ' +score.ToString ());
        Save save = CreateSaveGameObject();
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
        bf.Serialize(file, save);
        file.Close();
        //score=0;
        //scoreText.text = "积分:" + score.ToString ();
        Debug.Log("Game Saved");
    }
    private Save CreateSaveGameObject()     //存档数据
    {
        Save save = new Save();
        save.score=sc;
        return save;
    }
    public void NewGame()                 //新建游戏
    {
        Debug.Log("New Saved");
        score = 0;
        scoreText.text = "积分:" + score.ToString ();
    }
    public void Addscore()                //分数增加
    {
        score++;
        scoreText.text = "积分:" + score.ToString ();
    }
    public void LoadGame()              //读档
    { 
        Debug.Log("Load Saved");
        if (File.Exists(Application.persistentDataPath + "/gamesave.save"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save", FileMode.Open);
            Save save = (Save)bf.Deserialize(file);
            file.Close();
            scoreText.text ="积分:" + save.score;
            score = save.score;
            sc = score;
            Debug.Log("Game Loaded");
        }
        else
        {
            Debug.Log("No game saved!");
        }
    }
}

以上均为整理所得。

目录
相关文章
|
消息中间件 数据可视化 Java
RocketMQ保姆级教程
大家好,我是三友~~ 上周花了一点时间从头到尾、从无到有地搭建了一套RocketMQ的环境,觉得还挺easy的,所以就写篇文章分享给大家。
RocketMQ保姆级教程
|
10月前
|
机器学习/深度学习 传感器 运维
时间序列异常检测的5种方法:从统计阈值到深度学习
时间序列异常检测旨在识别偏离正常规律的数据点,如凌晨流量突增、传感器骤降等。因数据含趋势、季节性与噪声,需结合统计法(Z-Score)、移动平均、季节分解、Isolation Forest或自编码器等方法,多策略融合可有效降低误报。
1212 7
时间序列异常检测的5种方法:从统计阈值到深度学习
|
9月前
|
机器学习/深度学习 边缘计算 并行计算
基于MATLAB的语音信号处理与去噪全流程实现
基于MATLAB的语音信号处理与去噪全流程实现
646 1
|
XML Java Maven
Jar包下载失败的解决方案
Jar包下载失败的解决方案
1017 0
|
机器学习/深度学习 自然语言处理 算法
机器学习核心:监督学习与无监督学习
本文深入解析了机器学习中的监督学习与无监督学习,涵盖理论基础、应用场景及典型算法实现,如线性回归、决策树、K均值聚类和主成分分析,并通过代码示例加深理解。适合初学者和进阶者阅读。
1297 5
|
Shell Linux 网络安全
git生成SSH秘钥
git生成SSH秘钥
1322 2
|
Java API Spring
Spring Boot中的 6 种API请求参数读取方式
本文介绍了Spring Boot中6种常见的请求参数读取方式:@RequestParam用于加载URL查询参数,@PathVariable处理RESTful风格的URL路径参数,@MatrixVariable处理URL路径中的矩阵变量,@RequestBody用于读取POST/PUT请求的复杂请求体,@RequestHeader加载请求头信息,而@CookieValue则用于获取Cookie值。这些注解在不同场景下满足了API参数的多样化需求。
480 6
|
监控 安全 网络安全
|
监控 安全 数据挖掘
企业异地组网一般选用什么方案比较好?
企业异地组网可选用SD-WAN,它提供灵活、低成本且快速的解决方案。除此之外,还有光纤互联(费用高昂,不适合中小企业)和MPLS VPN(费用高,组网复杂)。SD-WAN能精准划分流量、支持多种接入方式、保障稳定性、简化部署并实现全局监控,是企业广域网建设的理想选择。
857 2