Unity3D中的常用方法

  备注:文中所使用的this均指脚本所依附的对象

1.移动(用Translate方法进行移动)

int moveSpeed = 10; //移动速度
this.transform.Translate(Vector3.down * Time.deltaTime * moveSpeed);

2. 修改Sprite Renderer的sprite

public Sprite[] sprites; //精灵数组
int frameIndex = 0; // 精灵数组索引

this.GetComponent<SpriteRenderer>().sprite = sprites[frameIndex];

2、游戏对象实例化(GameObject.Instantiate),及方法连续调用(InvokeRepeating)

using UnityEngine;
using System.Collections;

public class Gun : MonoBehaviour {

    public float rate = 0.2f ; //子弹发射速率

    public GameObject bullet; //子弹对象,bullet为预制物体

    void Start () {
        OpenFire ();
    }

    void Fire () { //实例化子弹
        GameObject.Instantiate(bullet, this.transform.position, Quaternion.identity);
    }

    void OpenFire () {
        InvokeRepeating("Fire", 1, rate); //重复调用Fire方法,1表示延迟1s后执行
    }
}

3、取消连续方法调用(CancelInvoke)

    public void StopFire () {
        CancelInvoke("Fire");
    }

4.unity3d中简单实现单例模式的方法(声明一个静态变量_instace,然后在Awake方法中赋值)

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public static GameManager _instance;

    void Awake () {
        _instance = this;
    }

}

 

原文地址:https://www.cnblogs.com/imteach/p/4235110.html