Unity3D 脚本手册

1、private Ray ray;  --定义射线

     ray = Camera.main.ScreenPointToRay(Input.mousePosition);  --摄像机发出的射线投射鼠标到屏幕中所碰到的第一个点

2、private RaycastHit hit;  --光线投射反馈,用来获取从raycast函数中得到的信息反馈的结构

     Physics.Raycast(ray, out hit) --使用物理类检查射线的碰撞  

  物理射线使用步骤

    第一步:创建一根射线。

    第二步:检查这根射线与其他物体的碰撞,得到碰撞信息。

    第三步:通过碰撞信息对碰撞到的物体进行处理。

if (Physics.Raycast(ray, out hit, Mathf.Infinity) && Input.GetMouseButtonDown(0))
        {          //射线,投射,长度(正无穷)
        GameObject.Destroy(hit.collider.gameobject);
        }

3、var mousePosition = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);  --二维向量,即dfgui界面

4、DragStart、DragEnd是在自身触发该事件,DragDrop是在碰到另一控件触发该事件。

5、动态给slicedSprite赋值,使用SpriteName属性就行。

6、单例模式:


public static 类 instance = null;
void Awake()
{
  //将该类的实例代入instance变量   _instance
= this; }

7、位置更新:


void FixUpdate()
{
    Vector2 pos = this.GetComponent<dfcontrol>().GUIManager.ScreenToGui(Input.mousePoint);//得到鼠标的位置
  Self.RelativePosition = new Vector3(pos.x-offsetpos.x,pos.y-offsetpos.y,0);//随着鼠标移动而移动
}

8、设置控件的z-order:

     BringToFont()--移到最上层

     SendToback()--移到最下层

9、获取鼠标在控件中的位置


Ray Ray = control.GetCamera().ScreenPointTORay(Input.mousePoint);
Vector2 offset = (control as dfSlicedSprite).GetHitPosition(ray);
类名.show(offset);

private static Vector2 offsetPos = new Vector2(0,0);
public static void show(spriteName,Vector2 hitPos)
{
    Instance.GetComponent<dfSlicedSprite>().SpriteName = spriteName;
    offsetPos = hitPos; 
}

10、实例化游戏物体:

        GameObject.Instantiate(object,Vector3,Quaternion);

(1)参数说明:

       Object:用于实例化的预制体;

       Vector3:实例化后生成的物体所在的位置;

       Quaternion[四元数]:实例化后生成的物体的旋转状态;

       Quaternion.identity:无旋转;

(2)构造随机位置

   位置是用 Vector3 类型进行表示的。

       X,Y,Z 三个值确定了物体在三维世界中的位置。

       Random.Range(min, max):生成随机数。

   在 min 和 max 直接随机生成一个随机数。

11、销毁游戏物体

       GameObject.Destroy(Object, float);定时销毁某个游戏物体。

   参数说明:

       Object:要销毁的游戏物体;

       float:时间,多少秒后销毁;

12、Invoke 函数

      Invoke(string,float):多少秒后执行某个函数[只会调用一次]。

 参数说明:

       String:要执行的函数的名称;

      Float:秒数,倒计时的时间;

13、nvokeRepeating(string,float,float)

      多少秒[第二个参数]后执行某个函数,并且以后每隔多少秒[第三个参数]都会执行该函数一次[重复调用 N 次]。

  参数说明:

      String:要执行的函数的名称;

      Float:秒数,准备时间,预热时间;

      Float:秒数,重复调用的间隔时间;

      CancelInvoke():取消这个脚本中所有的 Invoke 调用。

14、SendMessage 消息发送

    GameObject.SendMessage(string methodName,object value = null,SendMessageOptions options = SendMessageOptions.RequireReceiver):通知这个游戏物体身上的脚本文件中的“指定方法”执行。

    例如:enemy.SendMessage("TakeDamage",SendMessageOptions.DontRequireReceiver); 不接收命令。

  参数说明:

    第一个参数:方法名,要执行的方法的名称;

    第二个参数:向该方法传递的参数;

    第三个参数:是否必须有接收命令的选项,一般不要求接收命令。

15、协同程序

    在主程序运行时同时开启另一段逻辑处理,来协同当前程序的执行。但它与多线程程序不同,所有的协同程序都是在主线程序中运行的,它还是一个单线程程序。可以通过StartCoroutine()方法来启动一个协同程序。

    协同程序就是一个“代码片段”,往往我们需要将这个代码片段封装成一个方法,或者称之为函数。

void Start()
{
   StartCoroutine(doThing());//开启协同程序
}
IEnumerator doThing() {
yield return new WaitForSeconds (2);//协同程序休眠2秒
   Debug.Log ("dothing"); }

  参数说明:

    IEnumerator:协同程序的返回值类型;

    yield return:协同程序返回 xxxxx;

    new WaitForSeconds (秒数):实例化一个对象,等待多少秒后继续执行。

    这个 doThing()的作用就是等待两秒后,继续执行doThing

  开启协同程序:StartCoroutine(“协同程序方法名”);

  停止协同程序:StopCoroutine(“协同程序方法名”);

16、Time时间类

    Time.time --静态只读属性,游戏时间。从游戏开始到现在所经过的秒数。

    Time.deltaTime --静态只读属性,时间增量。渲染完上一帧画面所消耗的时间。[可以用于实现倒计时效果]

    Time.timescale --静态属性,时间缩放。[可以用于暂停游戏]当值为1时,游戏是正常状态;为0时,游戏是暂停状态;为0.5时,游戏是处于慢放0.5倍的状态。

17、Mathf数学类   

    Mathf.Abs() 取绝对值

    Mathf.Clamp(a,min,max) 将a限制在最小值和最大值之间

    Mathf.Lerp(from,to,a) 插入值,返回值=from+to(1-a)

    Mathf.Max() 取最大值

    Mathf.Min() 取最小值

    Mathf.Pow(a,b) a的b次方

    Mathf.Round() 四舍五入

18、挂在button1上的脚本,获得此button1button2作为游戏物体,可以获得挂在它上面的脚本;button3是获得其他的按钮。

    dfbutton  button1;
    GameObject button2;
    dfButton button3;     
void Start()   {    button1 = this.GetComponent<dfButton>();
       button2 = GameObject.Find("··· Button");
       button3= GameObject.Find("··· Button").GetComponent<dfButton>();   }
    void OnClick()
      {
       button2.GetComponent<挂在它上面的脚本>().字段 = 赋值;
       button2.GetComponent<dfButton>().IsEnabled = false;
     }

19、Quaternion.Euler 欧拉角

  例如:Quaternion.Euler(new Vector(0,180));  绕Y轴旋转180。

  Quaternion.identity 同一性 (实例化的时候用到)

  rigibody2D.MoveRotation(Random.Range(0f,180f));  物体旋转

20、Vector3.magnitude 长度

  例如:(player.position - transform.position).magnitude < 10f;两点之间的距离小于10。

21、游戏物体禁用:GameObject.SetActive(false);

  游戏脚本禁用:GetComponent<脚本名>().enabled = false;

  返回游戏对象是否激活的属性:bool GameObject.activeSelf.

22、Input.GetAxis

  Input.GetAxis("Horizontal")返回-1到1的值,通常在游戏对象做出平滑动作时使用。如果对键盘控制的即时性要求较高,就使用Input.GetAxisRaw("Horizontal")函数,该函数仅返回-1、0、1这3个值。

23、游戏对象移动

using UnityEngine;
using System.Collections;

public class PlayerControler : MonoBehaviour
{
    private Transform tr;
    public float speed = 10;//行走速度
    
    void Start ()
    {
        tr = GetComponent<Transform>();
    }
    
    void Update ()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Vector3 dir = h * Vector3.right + v * Vector3.forward;
        tr.Translate(dir * speed * Time.deltaTime,Space.Self);
    }
}

 24、在层次视图中查询父对象,获取其所有子节点的Transform组件,存入数组Points中

    public Transform[] points;

    points = GameObject.Find("MonsterPos").GetComponentsInChildren<Transform>(); if(points.Length > 0) { StartCoroutine(this.CreateMonster()); }

 25、UGUI射线事件

using UnityEngine.EventSystems;

    //当点击鼠标左键时
if (Input.GetMouseButtonDown(0))  
        {
            if (EventSystem.current.IsPointerOverGameObject())
            {
            //点到了UGUI
                Debug.Log(EventSystem.current.currentSelectedGameObject.name);
            }
            else  
            //没点到UGUI
            {
               
            }

        }          

 26、PlayerPrefs 数据存储与读取

//整数存储
int num = 10;
PlayerPrefs.SetInt("Number",num);
//整数读取
int num = PlayerPrefs.GetInt("Number");

其他接口:

PlayerPrefs.Save();//保存PlayerPrefs数据
PlayerPrefs.HasKey("HW");//是否存在该键
PlayerPrefs.DeleteKey("HW");//删除该键
PlayerPrefs.DeleteAll();//删除所有数据

注意:3种数据结构的键是共用的,比如有一个键"SomeKey",先用它来存储整数10,再用它来存储字符串"Hello",最后读取整数,结果为0,因为之前存在的10被覆盖了。

原文地址:https://www.cnblogs.com/jiangshuai52511/p/5496947.html