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!");
        }
    }
}

以上均为整理所得。

目录
相关文章
|
10月前
|
图形学
|
6天前
|
图形学
【unity小技巧】unity通过代码进行更改后处理效果
【unity小技巧】unity通过代码进行更改后处理效果
9 0
|
10月前
|
API 图形学
|
XML Java Android开发
每日记录自己的Android项目(一)——UI界面
由ViewBinding绑定好XML布局和根布局和标题栏。 还有个字段 private AppBarConfiguration appBarConfiguration;
82 0
|
编解码 自然语言处理 数据可视化
FL Studio 21新版更新全解析!2023年新增80项更新与改进!
FL Studio 21全称Fruity Loops Studio,就是大家熟悉的水果编曲软件,一个全能的音乐制作软件,包括编曲、录音、剪辑和混音等诸多功能,让你的电脑编程一个全能的录音室。FL Studio 21版本发布了,为我们带来了多种新功能,大大提高处理效率,轻松应对各种复杂的编曲任务,小编带来的是FL Studio 21中文版,内置中文补丁,可以切换成中文界面。 今天为大家展示了 FL STUDIO21 新增的插件,今天让我们看一看还有哪些新变化?
230 0
FL Studio 21新版更新全解析!2023年新增80项更新与改进!
SwiftUI—如何使列表同时支持删除和移动记录的功能
SwiftUI—如何使列表同时支持删除和移动记录的功能
122 0
SwiftUI—如何使列表同时支持删除和移动记录的功能
|
vr&ar 图形学 Android开发
【100个 Unity小知识点】 | 启动unity应用时的 Unity Logo 删除/替换的三种方案
Unity 小科普 老规矩,先介绍一下 Unity 的科普小知识: Unity是 实时3D互动内容创作和运营平台 。 包括游戏开发、美术、建筑、汽车设计、影视在内的所有创作者,借助 Unity 将创意变成现实。 Unity 平台提供一整套完善的软件解决方案,可用于创作、运营和变现任何实时互动的2D和3D内容,支持平台包括手机、平板电脑、PC、游戏主机、增强现实和虚拟现实设备。 也可以简单把 Unity 理解为一个游戏引擎,可以用来专业制作游戏!
|
编解码 监控 图形学
unity设置程序
unity设置程序 Application.runInBackground 后台运行 Application.dataPath 数据路径 Application.persistentDataPath 持久数据路径 Application.
991 0
|
C# 图形学 索引
C#6中的新增功能 【Unity3D亲测】
随着Unity2017的普及,使用.NET 4X的开发者也越来越多了,下面笔者给大家介绍一下在C# 6中的新功能主要是怕自己忘记,2333,有些功能还是很实用的~ 使用Unity版本2018.
1084 0

热门文章

最新文章