一些实用的Unity代码

判断是否存在文件夹,没有则创建
if (Directory.Exists(url) == false)
        {
            Directory.CreateDirectory(url);
        }
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
可以获取到这个值在数组中对应的key
数组.ToList().IndexOf(值)
设置角度和位置和大小
GameObject.Find(“Camera”).transform.position = new Vector3(0, 0, 0); 
GameObject.Find(“Camera”).transform.rotation=Quaternion.Euler(0, 0, 0); 
GameObject.Find(image + “(Clone)”).transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
获取时间并设置格式和类型
System.DateTime.Now.ToString(“yyMMddHHmmss”);
启动一个协程
StartCoroutine(name());
停止所有协程
StopAllCoroutines();
查找所有包含这个脚本并调用其中函数
脚本name[] handlers = (脚本name[])FindObjectsOfType(typeof(脚本name)); 
foreach (脚本name h in handlers) 

h.函数(); 
}
循环启动某个函数
Invoke(“ShowShare”, 0.2f);
解析txt文件
 public void Dropdown()
    {
        var fileAddress = System.IO.Path.Combine(Application.persistentDataPath + "/" + PublicStaticData.FolderName + "/", "Configure.txt");
        FileInfo fInfo0 = new FileInfo(fileAddress);
        string s = "";
        if (fInfo0.Exists)
        {
            StreamReader r = new StreamReader(fileAddress);
            s = r.ReadToEnd();
        }
        string[] wordsName = s.Split(',');
        PublicStaticData.imageNames = new string[wordsName.Length];
        for (int i = 0; i < wordsName.Length; i++)
        {
            string strResult = wordsName[i].Replace("\n", "").Replace(" ", "");//.Replace("\t", "").Replace("\r", "");
            PublicStaticData.imageNames[i] = strResult;
            inside.Add(strResult);
        }
        dropdown.AddOptions(inside);
        //cube.GetComponent<UnityEngine.UI.Image>().overrideSprite = Resources.Load("shipingimg", typeof(Sprite)) as Sprite;
        //dropdown.itemImage.sprite = Resources.Load("shipingimg", typeof(Sprite)) as Sprite;
    }

//写入txt
 var fileAddress = System.IO.Path.Combine(Application.streamingAssetsPath, "Key.txt");
        print(Application.streamingAssetsPath);
        FileInfo fInfo0 = new FileInfo(fileAddress);
        //string s = "";
        if (fInfo0.Exists)
        {
            StreamReader r = new StreamReader(fileAddress);
            key = r.ReadToEnd();
            r.Close();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
截图
 IEnumerator SeriousPhotoes()
    {
        yield return new WaitForEndOfFrame();
        Texture2D t = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        t.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
        t.Apply();

        // 然后将这些纹理数据,成一个jpg图片文件  
        byte[] bytes = t.EncodeToPNG();
        System.IO.File.WriteAllBytes(Application.persistentDataPath + "/fximg/" + i + ".jpg", bytes);
    }


    public void ShowShare()
    {
        if (File.Exists(Application.persistentDataPath + "/fximg/" + i + ".jpg"))
        {
            if (PublicStaticData.imageNamed != null)
            {
                VuforiaInteracting.Instance.Eliminate(PublicStaticData.imageNamed);
            }
            ShareUI();

            DefaultTrackableEventHandler[] handlers = (DefaultTrackableEventHandler[])FindObjectsOfType(typeof(DefaultTrackableEventHandler));
            foreach (DefaultTrackableEventHandler h in handlers)
            {
                h.OnEnabledTracking();
            }

            LoadFromFile(Application.persistentDataPath + "/fximg/" + i + ".jpg");
            Sprite tempSprite = new Sprite();
            tempSprite = Sprite.Create(m_Tex, new Rect(0, 0, m_Tex.width, m_Tex.height), new Vector2(0, 0));
            GameObject.Find("Photo").GetComponent<RawImage>().texture = tempSprite.texture;
        }
        else
        {
            Invoke("ShowShare", 0.2f);
        }
    }
    public static void DeleteFolder(string dir)
    {
        foreach (string d in Directory.GetFileSystemEntries(dir))
        {
            File.Delete(d);//直接删除其中的文件  
        }
    }
    private void LoadFromFile(string path)
    {
        m_Tex = new Texture2D(Screen.width, Screen.height);
        m_Tex.LoadImage(ReadPNG(path));
    }
    private byte[] ReadPNG(string path)
    {
        FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
        fileStream.Seek(0, SeekOrigin.Begin);
        byte[] binary = new byte[fileStream.Length];
        fileStream.Read(binary, 0, (int)fileStream.Length);
        fileStream.Close();
        fileStream.Dispose();
        fileStream = null;
        return binary;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
是否有这个文件
File.Exists(mp4Path) 
删除url下的文件 
File.Delete(url)
发送数据和解析服务器放回的json
 WWWForm formActivity = new WWWForm();
        formActivity.AddField("属性名", 数据);
        formActivity.AddField("属性名", 数据);
        formActivity.AddField("属性名", 数据);
        formActivity.AddField("属性名", 数据);
        WWW getActivityData = new WWW(PublicStaticData.GetDateUrl, formActivity);
        yield return getActivityData;
        string _mp4Url = "mp4Url";
        LitJson.JSONNode JsonData = LitJson.JSON.Parse(getActivityData.text);

        Get_mp4Url = JsonData[_mp4Url].ToString();

        if (xiazai && Get_mp4Url.Contains("http://"))
        {
            StartCoroutine(DownloadMp4(Get_mp4Url, imagename));
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
下载文件
 public IEnumerator DownloadMp4(string mp4Url, string mp4Name)
    {

        UpdateMp4Name = mp4Name;
        JhinTool.Instance.Folder(Application.persistentDataPath + "/" + PublicStaticData.FolderName);
        BundleMp4 = new WWW(mp4Url);
        yield return BundleMp4;
        SaveFile(mp4Name, BundleMp4.bytes);

    }
    private void SaveFile(string fname, byte[] bytes)
    {

        fileStream = File.Create(Application.persistentDataPath + "/" + PublicStaticData.FolderName + "/" + fname+".mp4");
        fileStream.Write(bytes, 0, bytes.Length);
        fileStream.Close();
        fileStream.Dispose();
    }
    this.BundleMp4.isDone判断是否下载
    this.BundleMp4.progress下载的比例
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
打开网址
Application.OpenURL(url);
自动旋转
this.transform.RotateAround(this.transform.position, Vector3.up, 0.25f);
点击事件

void OnTap(TapGesture gesture) 

需要添加一个插件,这是点击,下面是缩放和位移 
}


 void OnPinch(PinchGesture gesture)
    {
        //// 识别器当前状态(Started/Updated/Ended)
        //ContinuousGesturePhase phase = gesture.Phase;
        //// 当前两个手指的距离
        //float gap = gesture.Gap;
        // 当前与上一帧的变动值
        float delta = gesture.Delta;
        if (delta > 0 && this.transform.localScale.x < 3.0f)
            this.transform.localScale += new Vector3(0.1f, 0.1f, 0.1f);
        else if (delta < 0 && this.transform.localScale.x > 0.5f)
            this.transform.localScale -= new Vector3(0.1f, 0.1f, 0.1f);
    }
    //下面的函数是当鼠标触碰到碰撞体或者刚体时调用,我的碰撞体设置是mesh collider,然后别忘了,给这个collider添加物理材质      
    //值得注意的是世界坐标系转化为屏幕坐标系,Z轴是不变的  
    IEnumerator OnMouseDown()
    {
        //将物体由世界坐标系转化为屏幕坐标系 ,由vector3 结构体变量ScreenSpace存储,以用来明确屏幕坐标系Z轴的位置  
        Vector3 ScreenSpace = Camera.main.WorldToScreenPoint(transform.position);
        //完成了两个步骤,1由于鼠标的坐标系是2维的,需要转化成3维的世界坐标系,2只有三维的情况下才能来计算鼠标位置与物体的距离,offset即是距离  
        Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z));
        //当鼠标左键按下时  
        while (Input.GetMouseButton(0))
        {
            //得到现在鼠标的2维坐标系位置  
            Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, ScreenSpace.z);
            //将当前鼠标的2维位置转化成三维的位置,再加上鼠标的移动量  
            Vector3 CurPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
            //CurPosition就是物体应该的移动向量赋给transform的position属性        
            transform.position = CurPosition;
            //这个很主要  
            yield return new WaitForFixedUpdate();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
对字符操作
string sss = info.ztPositions.Replace(“],[“, “*”).Replace(“[[“, “”).Replace(“]]”, “”); 
string strResult = wordsName[i].Replace(“\n”, “”).Replace(” “, “”);//.Replace(“\t”, “”).Replace(“\r”, “”);
跳转场景
using UnityEngine.SceneManagement; 
SceneManager.LoadScene(“Main”);
代码挂载和添加btn事件
GameObject item_1 = Resources.Load(“xxx/item1”) as GameObject; 
通过代码添加uibtn的点击事件 
Button btn = btnObj.GetComponent(); 
btn.onClick.AddListener(delegate() { 
this.OnClick(btnObj); 
});
数学
//算2点距离 
public float GPSdistance(Point newpoint, Point nextgps) 

float A = Math.Abs(newpoint.X - nextgps.X); 
float B = Math.Abs(newpoint.Y - nextgps.Y); 
float C = Mathf.Sqrt(A * A + B * B); 
return C; 

float JD = (float)(Math.Atan2(Math.Abs(B), Math.Abs(A)) * 180 / Math.PI);
改变颜色
g_Points[i].GetComponent< Image>().color = new Color(160, 160, 160, 255);
其他

go.AddComponent<脚本>可以通过代码添加脚本 
Destroy是删除 
FixedUpdate()可以固定刷新频率,Update()每一帧刷新一次,LateUpdate()在每一帧结尾触发,比Update慢。Awake()最早的初始化

//隐藏public显示在面板上 
[HideInInspector] 
public string teststring = null; 
//可以让private显示在面板上 
//[SerializeField] 
//private int testint ; 
1、世界坐标→屏幕坐标:camera.WorldToScreenPoint(transform.position);这样可以将世界坐标转换为屏幕坐标。其中camera为场景中的camera对象。 
2、屏幕坐标→视口坐标:camera.ScreenToViewportPoint(Input.GetTouch(0).position);这样可以将屏幕坐标转换为视口坐标。其中camera为场景中的camera对象。 
3、视口坐标→屏幕坐标:camera.ViewportToScreenPoint(); 
4、视口坐标→世界坐标:camera.ViewportToWorldPoint(); 
第一种,被调用脚本函数为static类型,调用时直接用 脚本名.函数名()。很不实用…… 
第二种,GameObject.Find(“脚本所在物体名”).SendMessage(“函数名”); 此种方法可以调用public和private类型函数 
第三种,GameObject.Find(“脚本所在物体名”).GetComponent<脚本名>().函数名();此种方法只可以调用public类型函数

特殊文件夹
1.隐藏文件夹 
以.开头的文件夹会被Unity忽略。在这种文件夹中的资源不会被导入,脚本不会被编译。也不会出现在Project视图中。 
2.Standard Assets 
在这个文件夹中的脚本最先被编译。 
这个文件夹中的脚本会被导出到Assembly-CSharp-firstpass, Assembly-UnityScript-firstpass 或 Assembly-Boo-firstpass项目中,依语言而定。参考 http://docs.unity3d.com/Documentation/Manual/ScriptCompileOrderFolders.html 。在这个文件夹中的脚本比其他脚本都要先编译。将脚本放在这个文件夹里,就可以用C#脚本来访问js脚本或其他语言的脚本。 
3.Pro Standard Assets 
跟Standard Assets相同,只不过里面的文件是给Pro版本的Unity使用的。 
4.Editor 
以Editor命名的文件夹允许其中的脚本访问Unity Editor的API。如果脚本中使用了在UnityEditor命名空间中的类或方法,它必须被放在名为Editor的文件夹中。Editor文件夹中的脚本不会在build时被包含。 
在项目中可以有多个Editor文件夹。 
注意:如果在普通的文件夹下,Editor文件夹可以处于目录的任何层级。如果在特殊文件夹下,那Editor文件夹必须是特殊文件夹的直接子目录。 
5.Plugins 
Plugins文件夹用来放native插件。它们会被自动包含进build中去。注意这个文件夹只能是Assets文件夹的直接子目录。 
在Windows平台下,native 插件是dll文件;Mac OS X下,是bundle文件;Linux下,是.so文件。 
跟Standard Assets一样,这里的脚本会更早的编译,允许它们被之外的脚本访问。 
5.1.Plugins/x86 
如果为32bit或64bit平台创建游戏,那么这个文件夹下的native plugin文件会被自动的包含在游戏build中。如果这个文件夹不存在,则Unity会查找Plugins文件夹下的native pluglins。 
5.2.Plugins/x86_64 
如果为32bit或64bit平台创建游戏,那么这个文件夹下的native plugin文件会被自动的包含在游戏build中。如果这个文件夹不存在,则Unity会查找Plugins文件夹下的native pluglins。 
如果要创建universal build,建议你同时使用这两个文件夹。然后将32bit和64bit的native plugins放进相应的文件夹中。 
5.3.Plugins/Android 
在这个文件夹里放入Java.jar文件。用于java语言的plugins。.so文件也会被包含进来。参考 http://docs.unity3d.com/Documentation/Manual/PluginsForAndroid.html 
5.4.Plugins/iOS 
A limited, simple way to automatically add (as symbolic links) any .a, .m, .mm, .c, or .cpp files into the generated Xcode project. Seehttp://docs.unity3d.com/Documentation/Manual/PluginsForIOS.html 
If you need more control how to automatically add files to the Xcode project, you should make use of the PostprocessBuildPlayer feature. Doing so does not require you to place such files in the Plugins/iOS folder. Seehttp://docs.unity3d.com/Documentation/Manual/BuildPlayerPipeline.html 
6.Resources 
Resources文件夹允许你在脚本中通过文件路径和名称来访问资源。但还是推荐使用直接引用来访问资源。 
放在这一文件夹的资源永远被包含进build中,即使它没有被使用。因为Unity无法判断脚本有没有访问了其中的资源。 
项目中可以有多个Resources文件夹,因此不建议在多个文件夹中放同名的资源。 
一旦build游戏,Resources文件夹中的所有资源被打包进游戏存放资源的archive中。这样在游戏的build中就不存在Resources文件夹了。即使脚本中仍然使用了资源在项目中的路径。参考  http://docs.unity3d.com/Documentation/Manual/LoadingResourcesatRuntime.html 
注意:当资源作为脚本变量被访问时,这些资源在脚本被实例化后就被加载进内存。如果资源太大,你可能不希望它被这样加载。那么你可以将这些大资源放进Resources文件夹中,通过Resources.Load来加载。当不再使用这些资源了,可以通过Destroy物体,再调用Resources.UnloadUnusedAssets来释放内存。 
7.Editor Default Resources 
这是为editor 脚本使用的文件夹。 
8.Gizmos 
Gizmos文件夹存放用Gizmos.DrawIcon方法使用的贴图、图标资源。放在Gizmos文件夹中的贴图资源可以直接通过名称使用,可以被Editor作为gizmo画在屏幕上。 
9.WebPlayerTemplates 
用来替换web build的默认网页。这个文件夹中的脚本都不会被编译。这个文件夹必须作为Assets文件夹的直接子目录。 
10.StreamingAssets 
这里的文件会被拷贝到build文件夹中,不会修改(移动和网页版不同,他们会被嵌入到最终build文件中)。它们的路径会因平台而有差异,但都可以通过Application.streamingAssetsPath来访问。
截取字符串
string sModelName = this.name.Substring(4); 
.ToList().IndexOf(listname)

猜你喜欢

转载自blog.csdn.net/qq_27748027/article/details/80569574