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;
        }
	}
}

Vector2

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

public class API11Vector2 : MonoBehaviour {

    void Start()
    {
        /* 静态变量 */

        // up,down,left,right,one,zero:分别表示点(0,1)(0,-1)(-1,0)(1,0)(1,1)(0,0)
        print(Vector2.down);
        print(Vector2.up);
        print(Vector2.left);
        print(Vector2.right);
        print(Vector2.one);
        print(Vector2.zero);

        // x,y:x坐标,y坐标(如果有一个向量Vector2 vec,也可以使用vec[0]和vec[1]来表示x和y坐标)
        Vector2 vec1 = new Vector2(3, 4);
        Debug.Log("x:" + vec1.x);
        Debug.Log("x:" + vec1[0]);
        Debug.Log("y:" + vec1.y);
        Debug.Log("x:" + vec1[1]);

        // magnitude:向量的长度
        Debug.Log(vec1.magnitude);

		// sqrMagnitude:向量的长度的平方(即上面的没开根号前,如果只是用来比较的话,不需要开根号)
        Debug.Log(vec1.sqrMagnitude);

        // normalized:返回该向量的单位化向量(如果有一向量,返回一个新向量,方向不变,但长度变为1)
        Debug.Log(vec1.normalized);

		// normalize:返回自身,自身被单位化
        vec1.Normalize();
        Debug.Log("x:" + vec1.x);
        Debug.Log("y:" + vec1.y);

        // 向量是结构体,值类型,需要整体赋值
        transform.position = new Vector3(3, 3, 3);
        Vector3 pos = transform.position;
        pos.x = 10;
        transform.position = pos;


        /* 静态方法 */

        // Angle(a,b):返回两个向量的夹角
        Vector2 a = new Vector2(2, 2);
        Vector2 b = new Vector2(3, 4);
        Debug.Log(Vector2.Angle(a, b));

        // ClampMagnitude(a,length):限定长度,如果a>length,将向量a按比例缩小到长度为length
        Debug.Log(Vector2.ClampMagnitude(b, 2));

        // Distance(a,b):返回两个向量(点)之间的距离
        Debug.Log(Vector2.Distance(a, b));

        // Lerp(a,b,x):在向量a,b之间取插值。最终值为(a.x + a.x * (b.x - a.x), a.y + a.y * (b.y - a.y))
        Debug.Log(Vector2.Lerp(a, b, 0.5f));
        Debug.Log(Vector2.LerpUnclamped(a, b, 0.5f));

        // Max,Min:返回两向量最大最小
        Debug.Log(Vector2.Max(a, b));

        // + - * /:向量之间可以加减,不能乘除,可以乘除普通数字
        Vector2 res = b - a;//1,2
        print(res);
        print(res * 10);
        print(res / 5);
        print(a + b);
        print(a == b);

    }


    public Vector2 a = new Vector2(2, 2);
    public Vector2 target = new Vector2(10, 3);
    void Update()
    {
        // MoveTowards(a,b,speed):从a到b,速度为speed
        a = Vector2.MoveTowards(a, target, Time.deltaTime);
    }

}

Random:随机数

    静态方法:
        Range(a,b):生成>=a且<b的随机数    若a和b都为整数,则生成整数
        InitState(seed):使用随机数种子初始化状态
            Random.InitState((int)System.DateTime.Now.Ticks);
    静态变量:
        value:生成0到1之间的小数,包括0和1   
        state:获取当前状态(即随机数种子)    
        rotation:获取随机四元数
        insideUnitCircle:在半径为1的圆内随机生成位置(2个点)
            transition.position = Random.insideUnitCircle * 5;  在半径为5的圆内随机生成位置
        insideUnitSphere:在半径为1的球内随机生成位置(3个点)
            cube.position = Random.insideUnitSphere * 5;

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

public class API12Random : MonoBehaviour {

    void Start()
    {
        Random.InitState((int)System.DateTime.Now.Ticks);
        print(Random.Range(4, 10));
        print(Random.Range(4, 5f));

    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            print(Random.Range(4, 100));
            print((int)System.DateTime.Now.Ticks);
        }
        //cube.position = Random.insideUnitCircle * 5;
        this.transform.position = Random.insideUnitSphere * 5;
    }
}

四元数Quaternion

一个物体的transform组件中,rotation是一个四元数

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

public class API13Quaternion : MonoBehaviour {

    void Start()
    {
        // rotation:四元数
	    // eulerAngles:欧拉角,rotation中的x,y,z
        //this.transform.rotation = new Vector3(10, 0, 0);  错误,左边是四元数,右边是欧拉角
        this.transform.eulerAngles = new Vector3(10, 0, 0);
        print(this.transform.eulerAngles);
        print(this.transform.rotation);


        // Euler:将欧拉角转换为四元数
        // eulerAngles:将四元数转换为欧拉角
        this.transform.eulerAngles = new Vector3(45, 45, 45);
        this.transform.rotation = Quaternion.Euler(new Vector3(45, 45, 45));
        print(this.transform.rotation.eulerAngles);
    }

    public Transform player;
    public Transform enemy;
    void Update()
    {
        // LookRotation:控制Z轴的朝向,一般处理某个物体望向某个物体  案例:主角望向敌人
        // Lerp:插值,比Slerp快,但当角度太大的时候,没Slerp效果好
        // Slerp:插值         案例:主角缓慢望向敌人
        if (Input.GetKey(KeyCode.Space))
        {
            Vector3 dir = enemy.position - player.position;
            dir.y = 0;
            Quaternion target = Quaternion.LookRotation(dir);
            player.rotation = Quaternion.Lerp(player.rotation, target, Time.deltaTime);
        }
    }
}

刚体Rigibody

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

public class API14RigidbodyPosition : MonoBehaviour {

    public Rigidbody playerRgd;
    public Transform enemy;
    public int force = 10;

    void Update()
    {
        // position:可以使用刚体的position来改变位置,突然改变
        playerRgd.position = playerRgd.transform.position + Vector3.forward * Time.deltaTime * 10;

        // MovePosition(Vector3 position):移动到目标位置,有插值的改变
        playerRgd.MovePosition(playerRgd.transform.position + Vector3.forward * Time.deltaTime * 10);

        // rotation:可以使用刚体的rotation来控制旋转
        // MoveRotation:旋转,有插值的改变
        if (Input.GetKey(KeyCode.Space))
        {
            Vector3 dir = enemy.position - playerRgd.position;
            dir.y = 0;
            Quaternion target = Quaternion.LookRotation(dir);
            playerRgd.MoveRotation(Quaternion.Lerp(playerRgd.rotation, target, Time.deltaTime));
        }

        // AddForce:给物体添加一个力
        playerRgd.AddForce(Vector3.forward * force);
    }
}

Camera

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

public class API15Camera : MonoBehaviour {

    private Camera mainCamera;

    void Start()
    {
        // 获取摄像机
        //mainCamera= GameObject.Find("MainCamera").GetComponent<Camera>();
        mainCamera = Camera.main;
    }

    void Update()
    {
        // ScreenPointToRay:把鼠标点转换为射线
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

        // 射线碰撞到的游戏物体
        RaycastHit hit;
        bool isCollider = Physics.Raycast(ray, out hit);  //射线检测
        // 如果碰撞到物体,输出物体名字
        if (isCollider)
        {
            Debug.Log(hit.collider);
        }

        Ray ray = mainCamera.ScreenPointToRay(new Vector3(200, 200, 0));
        Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
    }
}

Application类

Application Datapath:

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

public class API16Application_xxxPath : MonoBehaviour {
    void Start()
    {
        // 数据路径,工程路径
        print(Application.dataPath);
        // 可以通过文件流读取的数据
        // 注:单独创建StreamingAssets文件夹,在此文件夹中的数据打包的时候不会进行处理
        print(Application.streamingAssetsPath);
        // 持久化数据
        print(Application.persistentDataPath);
        // 临时缓冲数据
        print(Application.temporaryCachePath);
    }
}

Application 常用:

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

public class API17Application : MonoBehaviour {

    void Start()
    {
        print(Application.identifier);// 标识 
        print(Application.companyName);// 公司名
        print(Application.productName);// 产品名字
        print(Application.installerName);// 安装名
        print(Application.installMode);
        print(Application.isEditor);
        print(Application.isFocused);
        print(Application.isMobilePlatform);
        print(Application.isPlaying);
        print(Application.isWebPlayer);
        print(Application.platform);
        print(Application.unityVersion);
        print(Application.version);
        print(Application.runInBackground);

        Application.Quit();// 退出应用
        Application.OpenURL("www.sikiedu.com");// 打开一个网址
        //Application.CaptureScreenshot("游戏截图");  // 弃用
        UnityEngine.ScreenCapture.CaptureScreenshot("游戏截图");//  截图,参数是保存截图的名字

    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //UnityEditor.EditorApplication.isPlaying = false;
            SceneManager.LoadScene(1);
        }
    }
}

场景管理SceneManager:

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

public class API18SceneManager : MonoBehaviour {

    void Start()
    {
        // 当前加载的场景数量
        print(SceneManager.sceneCount);
        // 在BuildSetting里的场景数量
        print(SceneManager.sceneCountInBuildSettings);
        // 得到当前场景  通过name可以获得名字
        print(SceneManager.GetActiveScene().name);
        // 根据index获取场景,注意index只能是已经加载场景的
        print(SceneManager.GetSceneAt(0).name);

        SceneManager.activeSceneChanged += OnActiveSceneChanged;
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    // 场景改变事件(要卸载的场景,要加载的场景)
    void OnActiveSceneChanged(Scene a, Scene b)
    {
        print(a.name);
        print(b.name);
    }

    // 加载场景(加载的场景,加载的模式)
    void OnSceneLoaded(Scene a, LoadSceneMode mode)
    {
        print(a.name + "" + mode);
    }

    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            // LoadScene:加载场景,可以通过名字或者序号加载 
            // LoadSceneAsync:异步加载,可以取得加载场景的进度
            //SceneManager.LoadScene(1);
            //SceneManager.LoadScene("02 - MenuScene");
            print(SceneManager.GetSceneByName("02 - MenuScene").buildIndex);
            SceneManager.LoadScene(1);
        }

    }
}

射线检测:

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

public class Player : MonoBehaviour {
	
	void Update () {
		// 创建一条射线:new Ray(起点,方向);
        Ray ray = new Ray(transform.position+transform.forward, transform.forward);

		// 检测碰撞:返回值表示是否碰撞到物体    Physics.Raycast(射线[, 距离]);
        //bool isCollider = Physics.Raycast(ray);    	//无限距离
        //bool isCollider = Physics.Raycast(ray, 1);    //检测1米距离
		
		// 检测碰撞到哪个物体:  Physics.Raycast(射线, 碰撞信息);
        RaycastHit hit;
        //bool isCollider = Physics.Raycast(ray, out hit);
		
		// 碰撞检测时只检测某些层:  Physics.Raycast(射线, 距离, 检测层);
		// Mathf.Infinity表示无限距
        bool isCollider = Physics.Raycast(ray, Mathf.Infinity, LayerMask.GetMask("Enemy1", "Enemy2", "UI"));
        
        Debug.Log(isCollider);
        //Debug.Log(hit.collider);
        //Debug.Log(hit.point);
		
		//注:射线检测的重载方法有很多,不止以上几种
		//注:如果是2D的射线检测,要使用Physics2D.Raycast(),使用时要保证物体添加了2D碰撞器 
		//注:上面的方法只会检测碰撞到的第一个物体,如果要检测碰撞到的所有物体,使用RaycastAll(),返回RaycastHit数组 
    }
}

UGUI事件监听:3种方法

1 拖拽:

2 代码添加:

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

public class UIEventManager : MonoBehaviour {

    public GameObject btnGameObject;
    public GameObject sliderGameObject;
    public GameObject dropDownGameObject;
    public GameObject toggleGameObject;

	// Use this for initialization
	void Start () {
        btnGameObject.GetComponent<Button>().onClick.AddListener(this.ButtonOnClick);
        sliderGameObject.GetComponent<Slider>().onValueChanged.AddListener(this.OnSliderChanged);
        dropDownGameObject.GetComponent<Dropdown>().onValueChanged.AddListener(this.OnDropDownChanged);
        toggleGameObject.GetComponent<Toggle>().onValueChanged.AddListener(this.OnToggleChanged);
    }

    void ButtonOnClick()
    {
        Debug.Log("ButtonOnClick");
    }
    void OnSliderChanged(float value)
    {
        Debug.Log("SliderChanged:" + value);
    }
    void OnDropDownChanged(Int32 value)
    {
        Debug.Log("DropDownChanged:" + value);
    }
    void OnToggleChanged(bool value)
    {
        Debug.Log("ToggleChanged:" + value);
    }

    // Update is called once per frame
    void Update () {
		
	}
}

3 通过实现接口:通过这种方式,只能监听当前UGUI组件

    鼠标相关事件或拖拽相关事件的实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
//interface
public class UIEventManager2 : MonoBehaviour//, IPointerDownHandler,IPointerClickHandler,IPointerUpHandler,IPointerEnterHandler,IPointerExitHandler
    ,IBeginDragHandler,IDragHandler,IEndDragHandler,IDropHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("OnBeginDrag");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("OnDrag");
    }

    public void OnDrop(PointerEventData eventData)
    {
        Debug.Log("OnDrop");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("OnEndDrag");
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("OnPointerClick");
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("OnPointerDown");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("OnPointerEnter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("OnPointerExit");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("OnPointerUp");
    }
}

WWW类:下载专用

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

public class WWWTest : MonoBehaviour {

    public string url = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2622066562,1466948874&fm=27&gp=0.jpg";
    IEnumerator Start()
    {
        WWW www = new WWW(url);
        yield return www;
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = www.texture;
    }
}

角色控制器CharacterController:物体需要添加Character Controller组件

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

public class PlayerCC : MonoBehaviour {

    public float speed = 3;
    private CharacterController cc;

	// Use this for initialization
	void Start () {
        cc = GetComponent<CharacterController>();
        
	}
	
	void Update () {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        cc.SimpleMove(new Vector3(h, 0, v) * speed);//有重力效果
        //cc.Move(new Vector3(h, 0, v) * speed * Time.deltaTime);//无重力效果
        Debug.Log(cc.isGrounded);//是否在地面
	}
    private void OnControllerColliderHit(ControllerColliderHit hit)//自带的检测碰撞事件
    {
        Debug.Log(hit.collider);
    }
}

网格Mesh和材质Material

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

public class MeshAndMat : MonoBehaviour {
    public Mesh mesh;
    private Material mat;

	void Start () {
        //GetComponent<MeshFilter>().sharedMesh = mesh;//改变网格,样子跟着变
        //Debug.Log(GetComponent<MeshFilter>().mesh == mesh);//改变网格,样子不变
        mat = GetComponent<MeshRenderer>().material;
        
	}
	
	void Update () {
        mat.color = Color.Lerp(mat.color, Color.red, Time.deltaTime);//改变材质颜色
	}
}

unity 4.x   5.x   2017的异同

    GetComponent<Rigidbody2D>() 代替 rigidbody2D
    GetComponent<Rigidbody>() 代替 rigidbody
    GetComponent<AudioSource>() 代替 audio

    Unity 5.3:
    ParticleSystem main = smokePuff.GetComponent<ParticleSystem>();
    main.startColor
    Unity 5.5+:
    ParticleSystem.MainModule main = smokePuff.GetComponent<ParticleSystem>().main;
    main.startColor

    SceneManagement 代替 Application

    OnLevelWasLoaded() 在 Unity 5中被弃用了,使用OnSceneLoaded代替

		public class UnityAPIChange : MonoBehaviour {
			private Rigidbody rgd;
			void Start () {
				rgd = GetComponent<Rigidbody>();
				SceneManager.sceneLoaded += this.OnSceneLoaded;
			}
			void OnSceneLoaded(Scene scene, LoadSceneMode mode)
			{

			}
			
			void Update () {
				//rigidbody.AddForce(Vector3.one);
				//rgd.AddForce(Vector3.one);
				//audio.Play();//弃用的
				//GetComponent<AudioSource>().Play();
				//GetComponent<Rigidbody2D>();

				//GetComponent<MeshRenderer>();

				//Application.LoadLevel("Level2");
				SceneManager.LoadScene("Scene2");
				Scene scene = SceneManager.GetActiveScene();
				SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
			}

			private void OnLevelWasLoaded(int level)  弃用
			{
				
			}
		}

 

转载于:https://www.cnblogs.com/lmx282110xxx/p/10798725.html

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity3D常用API包括Component、Transform、GameObject、Object和Time等。\[1\]这些API可以用于处理游戏对象的组件、变换、实例化和销毁等操作。例如,可以使用Component来获取和管理游戏对象的组件,使用Transform来控制游戏对象的位置、旋转和缩放,使用GameObject来创建、查找和销毁游戏对象,使用Object来处理资源的加载和释放,使用Time来获取游戏的时间信息。此外,还有一些常见的API函数,如Instantiate函数用于实例化预制件,Start函数和Update函数用于处理游戏对象的初始化和更新等。\[2\]\[3\]这些API和函数是Unity开发中经常使用的工具,可以帮助开发者实现各种功能和效果。 #### 引用[.reference_title] - *1* [Unity3D数字孪生笔记——Unity常用API篇](https://blog.csdn.net/Lcl_huolitianji/article/details/120875486)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Unity3D常用API](https://blog.csdn.net/u011360242/article/details/77046732)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [【Unity 3D】常见API的讲解以及在C#脚本中的执行(附源码)](https://blog.csdn.net/jiebaoshayebuhui/article/details/128510864)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值