Unity3D入门 UnityAPI常用方法和类

时间函数:

这里只列举了一部分,更多的看Scripting API

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API02Time : MonoBehaviour {

	// Use this for initialization
	void Start () {
        Debug.Log("Time.deltaTime:" + Time.deltaTime);//完成最后一帧(只读)所需的时间(秒)
        Debug.Log("Time.fixedDeltaTime:" + Time.fixedDeltaTime);//执行物理和其他固定帧速率更新(如MonoBehaviour的FixedUpdate)的间隔,以秒为单位。
        Debug.Log("Time.fixedTime:" + Time.fixedTime);//最新的FixedUpdate启动时间(只读)。这是自游戏开始以来的时间单位为秒。
        Debug.Log("Time.frameCount:" + Time.frameCount);//已通过的帧总数(只读)。
        Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);//游戏开始后以秒为单位的实时时间(只读)。
        Debug.Log("Time.smoothDeltaTime:" + Time.smoothDeltaTime);//平滑的时间(只读)。
        Debug.Log("Time.time:" + Time.time);//此帧开头的时间(仅读)。这是自游戏开始以来的时间单位为秒。
        Debug.Log("Time.timeScale:" + Time.timeScale);//时间流逝的尺度。这可以用于慢动作效果。
        Debug.Log("Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);//此帧已开始的时间(仅读)。这是自加载上一个级别以来的秒时间。
        Debug.Log("Time.unscaledTime:" + Time.unscaledTime);//此帧的时间尺度无关时间(只读)。这是自游戏开始以来的时间单位为秒。

        float time0 = Time.realtimeSinceStartup;
        for(int i = 0; i < 1000; i++)
        {
            Method();
        }
        float time1 = Time.realtimeSinceStartup;
        Debug.Log("总共耗时:" + (time1 - time0));
	}

    void Method()
    {
        int i = 2;
        i *= 2;
        i *= 2;
    }
}

GameObject:

创建物体的3种方法:
    1 构造方法    
    2 Instantiate   可以根据prefab 或者 另外一个游戏物体克隆
    3 CreatePrimitive  创建原始的几何体

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API03GameObject : MonoBehaviour {

	void Start () {
        // 1 第一种,构造方法
        GameObject go = new GameObject("Cube");
        // 2 第二种
        //根据prefab 
        //根据另外一个游戏物体
        GameObject.Instantiate(go);
        // 3 第三种 创建原始的几何体
        GameObject.CreatePrimitive(PrimitiveType.Plane);
        GameObject go2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
	}
}

AddComponent:添加组件,可以添加系统组件或者自定义的脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API03GameObject : MonoBehaviour {

	void Start () {
        GameObject go = new GameObject("Cube");
        go.AddComponent<Rigidbody>();//添加系统组件
        go.AddComponent<API01EventFunction>();//添加自定义脚本
	}
}

禁用和启用游戏物体:
    activeSelf:自身的激活状态
    activeInHierarchy:在Hierarchy的激活状态
    SetActive(bool):设置激活状态

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API03GameObject : MonoBehaviour {

	void Start () {
        GameObject go = new GameObject("Cube");
        Debug.Log(go.activeInHierarchy);
        go.SetActive(false);
        Debug.Log(go.activeInHierarchy);
	}
}

游戏物体查找:

Find:按名称查找GameObject并返回它
FindObjectOfType:根据类型返回类型的第一个活动加载对象
FindObjectsOfType:根据类型返回类型的所有活动加载对象的列表
FindWithTag:根据标签返回一个活动的GameObject标记。如果没有找到GameObject,则返回NULL。
FindGameObjectsWithTag:根据标签返回活动游戏对象标记的列表。如果没有找到GameObject,则返回空数组。
transform.Find

GameObject.Find和transform.Find的区别: 
public static GameObject Find(string name); 
适用于整个游戏场景中名字为name的所有处于活跃状态的游戏对象。如果在场景中有多个同名的活跃的游戏对象,在多次运行的时候,结果是固定的。

public Transform Find(string name); 
适用于查找游戏对象子对象名字为name的游戏对象,不管该游戏对象是否是激活状态,都可以找到。只能是游戏对象直接的子游戏对象。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API03GameObject : MonoBehaviour {

	void Start () {
        Light light = FindObjectOfType<Light>();
        light.enabled = false;
        Transform[] ts = FindObjectsOfType<Transform>();
        foreach (Transform t in ts)
        {
            Debug.Log(t);
        }

        GameObject mainCamera = GameObject.Find("Main Camera");
        GameObject[] gos = GameObject.FindGameObjectsWithTag("MainCamera");
        GameObject gos1 = GameObject.FindGameObjectWithTag("Finish");
	}
}

游戏物体间消息的发送:

    BroacastMessage:发送消息,向下传递(子)
    SendMessage:发送消息,需要目标target
    SendMessageUpwards:发送消息,向上传递(父)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API04Message : MonoBehaviour {
    private GameObject son;
	
	void Start () {
        son = GameObject.Find("Son");

        // 向下传递消息  
        // SendMessageOptions.DontRequireReceiver表示可以没有接收者
        //BroadcastMessage("Test", null, SendMessageOptions.DontRequireReceiver);
        // 广播消息
        son.SendMessage("Test", null, SendMessageOptions.DontRequireReceiver);
        // 向上传递消息	
        //SendMessageUpwards("Test", null, SendMessageOptions.DontRequireReceiver);
	}
	
}

查找游戏组件:

GetComponet(s):查找单个(所有)游戏组件
GetComponet(s)InChildren:查找children中单个(所有)游戏组件
GetComponet(s)InParent:查找parent中单个(所有)游戏组件

注意:如果是查找单个,若找到第一个后,直接返回,不再向后查找

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API05GetComponent : MonoBehaviour {

	void Start () {
        Light light = this.transform.GetComponent<Light>();
        light.color = Color.red;
	}
	
}

函数调用Invoke:

    Invoke:调用函数
    InvokeRepeating:重复调用
    CancelInvoke:取消调用
    IsInvoking:函数是否被调用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API06Invoke : MonoBehaviour {

	void Start () {
        // Invoke(函数名,延迟时间)
        //Invoke("Attack", 3);	

        // InvokeRepeating(函数名,延迟时间,调用间隔)
        InvokeRepeating("Attack", 4, 2);

        // CancelInvoke(函数名)
        //CancelInvoke("Attack");
	}

    void Update()
    {
        // 判断是否正在循环执行该函数
        bool res = IsInvoking("Attack");
        print(res);
    }

    void Attack()
    {
        Debug.Log("开始攻击");
    }
}

协同程序:

    定义使用IEnumerator
    返回使用yield
    调用使用StartCoroutine
    关闭使用StopCoroutine
                StopAllCoroutine
    延迟几秒:yield return new WaitForSeconds(time);

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API08Coroutine : MonoBehaviour
{
    public GameObject cube;
    private IEnumerator ie;

    void Start()
    {
        print("协程开启前");
        StartCoroutine(ChangeColor());
        //协程方法开启后,会继续运行下面的代码,不会等协程方法运行结束才继续执行
        print("协程开启后");
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ie = Fade();
            StartCoroutine(ie);
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            StopCoroutine(ie);
        }
    }

    IEnumerator Fade()
    {
        for (; ; )
        {
            Color color = cube.GetComponent<MeshRenderer>().material.color;
            Color newColor = Color.Lerp(color, Color.red, 0.02f);
            cube.GetComponent<MeshRenderer>().material.color = newColor;
            yield return new WaitForSeconds(0.02f);
            if (Mathf.Abs(Color.red.g - newColor.g) <= 0.01f)
            {
                break;
            }
        }
    }

    IEnumerator ChangeColor()
    {
        print("hahaColor");
        yield return new WaitForSeconds(3);
        cube.GetComponent<MeshRenderer>().material.color = Color.blue;
        print("hahaColor");
        yield return null;
    }
}

鼠标相关事件函数:

    OnMouseDown:鼠标按下
    OnMouseUp:鼠标抬起
    OnMouseDrag:鼠标拖动
    OnMouseEnter:鼠标移上
    OnMouseExit:鼠标移开
    OnMouseOver:鼠标在物体上
    OnMouseUpAsButton:鼠标移开时触发,且移上和移开在同一物体上才会触发

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API08OnMouseEventFunction : MonoBehaviour {

    void OnMouseDown()
    {
        print("Down"+gameObject);
    }
    void OnMouseUp()
    {
        print("up" + gameObject);
    }
    void OnMouseDrag()
    {
        print("Drag" + gameObject);
    }
    void OnMouseEnter()
    {
        print("Enter");
    }
    void OnMouseExit()
    {
        print("Exit");
    }
    void OnMouseOver()
    {
        print("Over");
    }
    void OnMouseUpAsButton()
    {
        print("Button" + gameObject);
    }
	
}

Mathf类:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API09Mathf : MonoBehaviour {

    public Transform cube;
    public int a = 8;
    public int b = 20;
    public float t = 0;
    public float speed = 3;
    void Start()
    {
        /* 静态变量 */
        // 度数--->弧度
        print(Mathf.Deg2Rad);
        // 弧度--->度数
        print(Mathf.Rad2Deg);
        // 无穷大
        print(Mathf.Infinity);
        // 无穷小
        print(Mathf.NegativeInfinity);
        // 无穷小,接近0    
        print(Mathf.Epsilon);
        // π
        print(Mathf.PI);


        /* 静态方法 */
        // 向下取整
        Debug.Log(Mathf.Floor(10.2F));
        Debug.Log(Mathf.Floor(-10.2F));

        // 取得离value最近的2的某某次方数
        print(Mathf.ClosestPowerOfTwo(2));//2
        print(Mathf.ClosestPowerOfTwo(3));//4
        print(Mathf.ClosestPowerOfTwo(4));//4
        print(Mathf.ClosestPowerOfTwo(5));//4
        print(Mathf.ClosestPowerOfTwo(6));//8
        print(Mathf.ClosestPowerOfTwo(30));//32

        // 最大最小值
        print(Mathf.Max(1, 2, 5, 3, 10));//10
        print(Mathf.Min(1, 2, 5, 3, 10));//1

        // a的b次方
        print(Mathf.Pow(4, 3));//64 
        // 开平方根
        print(Mathf.Sqrt(3));//1.6

        cube.position = new Vector3(0, 0, 0);
    }

    void Update()
    {
        // Clamp(value,min,max):把一个值限定在一个范围之内
        cube.position = new Vector3(Mathf.Clamp(Time.time, 1.0F, 3.0F), 0, 0);
        Debug.Log(Mathf.Clamp(Time.time, 1.0F, 3.0F));

        // Lerp(a,b,t):插值运算,从a到b的距离s,每次运算到这个距离的t*s
        // Lerp(0,10,0.1)表示从0到10,每次运动剩余量的0.1,第一次运动到1,第二次运动到0.9...
        //print(Mathf.Lerp(a, b, t));

        float x = cube.position.x;
        //float newX = Mathf.Lerp(x, 10, Time.deltaTime);
        // MoveTowards(a,b,value):移动,从a到b,每次移动value
        float newX = Mathf.MoveTowards(x, 10, Time.deltaTime*speed);
        cube.position = new Vector3(newX, 0, 0);

        // PingPong(speed,distance):像乒乓一样来回运动,速度为speed,范围为0到distance
        print(Mathf.PingPong(t, 20));
        cube.position = new Vector3(5+Mathf.PingPong(Time.time*speed, 5), 0, 0);
    }
    
}

Input类:

    静态方法:
        GetKeyDown(KeyCode):按键按下
        GetKey(KeyCode):按键按下没松开
        GetKeyUp(KeyCode):按键松开
            KeyCode:键盘按键码,可以是键码(KeyCode.UP),也可以是名字("up")
        GetMouseButtonDown(0 or 1 or 2):鼠标按下
        GetMouseButton(0 or 1 or 2):鼠标按下没松开
        GetMouseButtonUp(0 or 1 or 2):鼠标松开
            0:左键    1:右键      2:中键
        GetButtonDown(Axis):虚拟按键按下
        GetButton(Axis):虚拟按键按下没松开
        GetButtonUp(Axis):虚拟按键松开
            Axis:虚拟轴名字
        GetAxis(Axis):返回值为float,上面的是返回bool
            cube.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal")*10);
    静态变量:
        anyKeyDown:任何键按下(鼠标+键盘)
        mousePosition:鼠标位置

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class API10Input : MonoBehaviour {

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            print("KeyDOwn");
        }
        if (Input.GetKeyUp(KeyCode.Space))
        {
            print("KeyUp");
        }
        if (Input.GetKey(KeyCode.Space))
        {
            print("Key");
        }


        if (Input.GetMouseButton(0))
            Debug.Log("Pressed left click.");


        if (Input.GetMouseButtonDown(0))
            Debug.Log("Pressed left click.");


        if (Input.GetButtonDown("Horizontal"))
        {
            print("Horizontal Down");
        }

        // GetAxis:这样使用有加速减速效果,如果是速度改变等情况不会突变
        //this.transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal") * 10);

        //GetAxisRaw:没有加速减速效果,速度改变等情况直接突变
        this.transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxisRaw("Horizontal") * 10);


        if (Input.anyKeyDown)
        {
            print("any key down");
        }

        print(Input.mousePosition);

    }
}

Input输入类之触摸事件:  推荐使用Easytouch插件

    Input.touches.Length:触摸点个数

    Input.touches[i]:获取第i个触摸点信息

    touch1.position:触摸点位置

    touch1.phase:触摸点状态

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchTest : MonoBehaviour {

	// Update is called once per frame
	void Update () {
        //Debug.Log(Input.touches.Length);
        if (Input.touches.Length > 0)
        {
            Touch touch1 = Input.touches[0];
            //touch1.position;
            TouchPhase phase  = touch1.phase;
        }
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40338728/article/details/81701430