Get it on Google Play


Wm뮤 :: 'Unity' 카테고리의 글 목록 (19 Page)

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
전자과 게임프로그래머 (퇴사함)
2022.3.22f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


'Unity'에 해당되는 글 186건

  1. 2020.10.19 TTS
  2. 2020.10.05 유니티 에디터 관련
  3. 2020.09.24 유니티 Mask
  4. 2020.09.01 failed to connect to localhost port 80: Connection
  5. 2020.08.25 c# MD5
  6. 2020.08.20 UnityWebRequest
  7. 2020.08.19 유니티 IDE(비주얼스튜디오) 바꾸기
  8. 2020.08.11 형변환 모음

TTS

2020. 10. 19. 15:05 Unity

 

 

    void DownloadTTS(string folderPath, string text, string fileName)
    {
        if (System.IO.Directory.Exists(folderPath) == false)
        {
            Debug.Log($"System.IO.Directory.CreateDirectory(folderPath), folderPath: {folderPath}");
            System.IO.Directory.CreateDirectory(folderPath);
        }
        var filePath = $"{folderPath}/{fileName}.mp3"; 
        if (CheckFile(filePath) == false)
        {
            StartCoroutine(DownloadFile("http://" + $@"translate.google.com/translate_tts?ie=UTF-8&textlen=32&client=tw-ob&q={text.Substring(0, Mathf.Min(200, text.Length))}&tl=en-gb", filePath));
        }
    }

Web에서 긁어오는 타입

200자 제한

일본어는 ja다

 

 

 

 

 

원샷타입


IEnumerator TextToSpeech(string text)
{
    Debug.Log($"TextToSpeech({text})");
    if (string.IsNullOrWhiteSpace(text))
    {
        Debug.Log($"빈문자열이라 정지");
        yield break;
    }
    var co = LoadAudioClipMP3($@"http://translate.google.com/translate_tts?ie=UTF-8&textlen=32&client=tw-ob&q={text.Substring(0, Mathf.Min(200, text.Length))}&tl=en-gb");
    StartCoroutine(co);
    yield return new WaitUntil(() => co?.Current as AudioClip != null);

    var audio = (AudioClip)co.Current;
    var obj = new GameObject("WebTTS-" + text);
    var audioSource = obj.AddComponent<AudioSource>();
    audioSource.PlayOneShot(audio);
    Debug.Log($"오디오 길이 {audio.length}초");
    Destroy(obj, audio.length + 1); //오디오 시간에 1초를 추가(여유분)

    yield return null;
}
static IEnumerator LoadAudioClipMP3(string downloadLink)
{
    Debug.Log($"LoadAudioClipMP3({downloadLink})");
    UnityWebRequest unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(downloadLink, AudioType.MPEG);

    var operation = unityWebRequest.SendWebRequest();

    yield return new WaitUntil(() => operation.isDone);

    if (unityWebRequest.isNetworkError)
    {
        Debug.LogError(unityWebRequest.error);
    }
    else
    {
        Debug.Log("LoadAudioClipSuccess");
    }
    var clip = DownloadHandlerAudioClip.GetContent(unityWebRequest);
    clip.name = downloadLink;
    yield return clip;
}

 

 

 

 

 

위에서 딕셔너리 추가버전

Dictionary<string, AudioClip> ttsDict = new Dictionary<string, AudioClip>();

AudioSource lastTTS;
IEnumerator TextToSpeech(string text)
{
    Debug.Log($"TextToSpeech({text})");
    if (string.IsNullOrWhiteSpace(text))
    {
        Debug.Log($"빈문자열이라 정지");
        yield break;
    }

    AudioClip audio;

    if (ttsDict.ContainsKey(text))
    {
        Debug.Log($"딕셔너리에서 가져옴({text})");
        audio = ttsDict[text];
    }
    else
    {
        var co = LoadAudioClipMP3($@"http://translate.google.com/translate_tts?ie=UTF-8&textlen=32&client=tw-ob&q={text.Substring(0, Mathf.Min(200, text.Length))}&tl=ja");
        StartCoroutine(co);
        yield return new WaitUntil(() => co?.Current as AudioClip != null);

        audio = (AudioClip)co.Current;
        ttsDict.Add(text, audio);
    }
    var obj = new GameObject("WebTTS-" + text);
    var audioSource = obj.AddComponent<AudioSource>();
    if (lastTTS!=null)
    {
        Destroy(lastTTS);
    }
    lastTTS = audioSource;
    audioSource.PlayOneShot(audio);
    //audioSource.pitch = 1.2f;
    Debug.Log($"오디오 길이 {audio.length}초");
    Destroy(obj, audio.length + 1); //오디오 시간에 1초를 추가(여유분)

    yield return null;
}
static IEnumerator LoadAudioClipMP3(string downloadLink)
{
    Debug.Log($"LoadAudioClipMP3({downloadLink})");
    UnityWebRequest unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(downloadLink, AudioType.MPEG);

    var operation = unityWebRequest.SendWebRequest();

    yield return new WaitUntil(() => operation.isDone);

    if (unityWebRequest.isNetworkError)
    {
        Debug.LogError(unityWebRequest.error);
    }
    else
    {
        Debug.Log("LoadAudioClipSuccess");
    }
    var clip = DownloadHandlerAudioClip.GetContent(unityWebRequest);
    clip.name = downloadLink;
    yield return clip;
}

 

 

 

 

 

 

 

 

 

 

'Unity' 카테고리의 다른 글

유니티 내비게이션 navigation  (0) 2020.10.25
유니티 Mask  (0) 2020.09.24
유니티 IDE(비주얼스튜디오) 바꾸기  (0) 2020.08.19
posted by 모카쨩
2020. 10. 5. 11:00 Unity/C#

 

gui색을 노란색으로 바꿈

GUILayout도 적용됨

GUI.backgroundColor = Color.yellow;
{
    GUILayout.Box(nameof(gameclass.name), GUILayout.Width(50), GUILayout.Height(50));
}
GUI.backgroundColor = Color.white;

 

 

가로전환

GUILayout.BeginHorizontal();
{
}
GUILayout.EndHorizontal();

 

스크롤뷰(슬라이더)

Vector2 scrollPosition=Vector2.zero;
void OnGUI()
{
    //scrollPosition=GUILayout.BeginScrollView(scrollPosition, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
    scrollPosition=GUILayout.BeginScrollView(scrollPosition);
    { 
    }
    GUILayout.EndScrollView();
}

 

스크롤뷰(슬라이더) v2 (미완성)

Vector2 scrollPosition=Vector2.zero;
void OnGUI()
{
    scrollPosition = GUI.BeginScrollView(new Rect(0, 0, position.width, position.height), scrollPosition, new Rect(0, 0, width:500, height:800));
    {
    }
    GUI.EndScrollView();
}

 

 

 

 

 

마우스 대면 바뀌는 주석

        if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
            GUILayout.Label("Mouse over!");
        else
            GUILayout.Label("Mouse somewhere else");

 

버튼

if(GUILayout.Button("버튼"))
{

}

 

 

 

왼쪽으로 밀린 박스

    var Texture2D = new Texture2D(1, 1);//삭제가 안되어 메모리릭을 유발하므로 전역에 생성해 두어야함


{ 
    BoxBG.SetPixels(0,0,1,1, new Color[]{ Color.gray});
    BoxBG.Apply();

    var guiStyle = new GUIStyle();
    guiStyle.alignment = TextAnchor.UpperLeft;
    guiStyle.richText = true;
    guiStyle.normal.background = BoxBG;

    GUILayout.Box("내용",guiStyle);
}

 

 

 

인스펙터 변동사항이 있는지 검사한다

겸 드롭다운 샘플

EditorGUI.BeginChangeCheck();
{
    index = EditorGUILayout.Popup("Index", index, new string[] { "1", "2" });
}
if (EditorGUI.EndChangeCheck())
{
    Debug.Log("index값이 변경됨");
}

 

 

들여쓰기

EditorGUILayout계열만 적용됨

GUILayout은 안됨

EditorGUI.indentLevel++;
{


}
EditorGUI.indentLevel--;

 

 

 

스크립트오브젝트저장

//더티플래그

EditorUtility.SetDirty(scriptableObject);
var filePath = AssetDatabase.GetAssetPath(scriptableObject);
Debug.Log($"scriptableObject 저장됨, filePath: {filePath}");
//AssetDatabase.SaveAssets(); //이건 딱히 안 넣어도 되는듯

 

 

애니메이션 상태 저장

ImportAsset이 붙은 이유는 이래야 저장되더라

아마 위도 동일할듯 싶은데 나중에 해봐야지

https://github.com/ahzkwid/AhzkwidAvatarTools/blob/main/Assets/Ahzkwid/AvatarTools/CreatorTools/Editor/AnimationRepairTool.cs

여기서 사용함

UnityEditor.AssetDatabase.SaveAssetIfDirty(animationClip);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(animationClip));

 

 

 

 

 

패스 에디터

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

#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(PayloadRace))]
public class PayloadRaceEditor : Editor
{
    private Vector3 position = Vector3.zero;

    void OnSceneGUI()
    {
        var payloadRace = (PayloadRace)target;
        var tracksParent = payloadRace.tracksParent;
        if (tracksParent)
        {
            var childs = new List<Transform>();
            for (int i = 0; i < tracksParent.childCount; i++)
            {
                childs.Add(tracksParent.GetChild(i));
            }
            foreach (var child in childs)
            {
                if (Vector3.Distance(payloadRace.transform.position, child.position) < 1)
                {
                    //너무 가까우면 최상위 조작이 불가하므로
                    continue;
                }
                var newPosition = UnityEditor.Handles.PositionHandle(child.position, child.rotation);
                if (newPosition != child.position)
                {
                    UnityEditor.Undo.RecordObject(child, "Move Transform");
                    child.position = newPosition;
                }
            }
        }
    }
}
#endif
public class PayloadRace : MonoBehaviour
{
    public int team = 0;
    public GameObject payload;
    public Transform tracksParent;
#if UNITY_EDITOR_WIN
    void OnDrawGizmos()
    {
        var color = Color.red;
        if (team == 0)
        {
            color = Color.blue;
        }
        Gizmos.color = color;
        {
            Gizmos.DrawWireSphere(transform.position,5);
        }
        Gizmos.color = Color.white;

        if (tracksParent)
        {
            var childs = new List<Transform>();
            for (int i = 0; i < tracksParent.childCount; i++)
            {
                childs.Add(tracksParent.GetChild(i));
            }
            foreach (var child in childs)
            {
                Gizmos.DrawSphere(child.position,0.1f);
                if (Vector3.Distance(transform.position, child.position)<1)
                {
                    continue;
                }
            }
            for (int i = 0; i < childs.Count-1; i++)
            {
                Gizmos.DrawLine(childs[i].position, childs[i + 1].position);
            }
        }
    }
#endif
    // Start is called before the first frame update
    void Start()
    {
        
    }

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

'Unity > C#' 카테고리의 다른 글

그래디언트효과  (0) 2020.10.20
failed to connect to localhost port 80: Connection  (0) 2020.09.01
c# MD5  (0) 2020.08.25
posted by 모카쨩
2020. 9. 24. 11:17 Unity

 

 

 

 

해당 오브젝트 하위의 이미지등이 rect 안에서만 보임

alpha값은 1/255 이상이여야 하고 0이면 안됨

적용이 잘 안 된다면 Mask컴포넌트를 지웠다가 재할당 할것

'Unity' 카테고리의 다른 글

TTS  (0) 2020.10.19
유니티 IDE(비주얼스튜디오) 바꾸기  (0) 2020.08.19
유니티 콜라보레이트 클라우드  (0) 2020.08.10
posted by 모카쨩
2020. 9. 1. 12:36 Unity/C#

 

 

파일 주소앞에 file:///를 넣는다

 

 

'Unity > C#' 카테고리의 다른 글

유니티 에디터 관련  (0) 2020.10.05
c# MD5  (0) 2020.08.25
UnityWebRequest  (0) 2020.08.20
posted by 모카쨩
2020. 8. 25. 17:17 Unity/C#

v1

    public string GetMD5(byte[] data)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        byte[] hash = System.Security.Cryptography.MD5.Create().ComputeHash(data);
        foreach (byte b in hash)
        {
            sb.Append(b.ToString("X2"));
        }
        return sb.ToString();
    }

 

 

v2

public string GetMD5(byte[] data)
{
    byte[] bytes = System.Security.Cryptography.MD5.Create().ComputeHash(data);
    return System.BitConverter.ToString(bytes).Replace("-", "");
}

'Unity > C#' 카테고리의 다른 글

failed to connect to localhost port 80: Connection  (0) 2020.09.01
UnityWebRequest  (0) 2020.08.20
형변환 모음  (0) 2020.08.11
posted by 모카쨩
2020. 8. 20. 15:54 Unity/C#

파일을 다운로드

    public string url;
    public string fileName;
    public string fileType;
    IEnumerator DownloadFile()
    {
        string filePath= $"{Application.persistentDataPath}/{fileName}";
        if( (fileType != null)&& (fileType.Trim() != "") )
        {
            filePath += $".{fileType}";
        }
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
        yield return unityWebRequest.SendWebRequest();
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
        }
    }

 

 

V2




    /// <summary>
    /// 다운 다되면 파일경로를 반환
    /// </summary>
    /// <param name="downloadlink"></param>
    /// <param name="filePath"></param>
    /// <returns></returns>
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        Debug.Log($"Download:{downloadlink}");
        {
            DOWNLOAD_RETRY:;
            {
                var unityWebRequest = UnityWebRequest.Get(downloadlink);
                var operation = unityWebRequest.SendWebRequest();
                yield return new WaitUntil(() => operation.isDone);

                if (unityWebRequest.isNetworkError)
                {
                    Debug.LogError(unityWebRequest.error);
                    yield return new WaitForSeconds(3f);
                    goto DOWNLOAD_RETRY;
                }
                else
                {
                    Debug.Log(filePath);

                    var folderPath = System.IO.Path.GetDirectoryName(filePath);
                    Debug.Log(folderPath);
                    if (System.IO.Directory.Exists(folderPath) == false)//폴더가 없으면 생성
                    {
                        System.IO.Directory.CreateDirectory(folderPath);
                    }
                    System.IO.File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
                }
            }
        }
        yield return filePath;
    }

 

 

 

 

 

DownloadHandlerFile 방식 

메모리를 딱 필요한만큼만 쓴다. 위에는 2배사용

V3



    List<string> downloadList = new List<string>();
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        downloadList.Add(downloadlink);

        DOWNLOADRETRY:;
        {
            UnityWebRequest unityWebRequest = UnityWebRequest.Get(downloadlink);
            unityWebRequest.downloadHandler = new DownloadHandlerFile(filePath);

            var operation = unityWebRequest.SendWebRequest();
            yield return new WaitUntil(() => operation.isDone);

            if (unityWebRequest.isNetworkError)
            {
                Debug.LogError(unityWebRequest.error);
                yield return new WaitForSeconds(1f);
                goto DOWNLOADRETRY;
            }
            else
            {
                Debug.Log(filePath);
            }
        }
        downloadList.Remove(downloadlink);
    }

 

V1~V2

더보기
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(downloadlink);
        unityWebRequest.downloadHandler = new DownloadHandlerFile(filePath);
        var operation = unityWebRequest.SendWebRequest();
        while (!operation.isDone)
        {
            yield return new WaitForSeconds(0.01f);
        }
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            Debug.Log(filePath);
        }
    }

 

 

 

V2

List<String> DownloadList = new List<String>();
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(downloadlink);
        unityWebRequest.downloadHandler = new DownloadHandlerFile(filePath);

        DownloadList.Add(downloadlink);
        DOWNLOADRETRY:;
        var operation = unityWebRequest.SendWebRequest();
        while (!operation.isDone)
        {
            yield return new WaitForSeconds(0.01f);
        }
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
            yield return new WaitForSeconds(1f);
            goto DOWNLOADRETRY;
        }
        else
        {
            Debug.Log(filePath);
        }
        DownloadList.RemoveAt(DownloadList.FindIndex(0, DownloadList.Count, x => x == downloadlink));
    }

 

 

 

 

 

 

HTML 다운로드

    public string urlSample= "https://wmmu.tistory.com/";
    IEnumerator DownloadHTML(string url)
    {
        UnityWebRequest unityWebRequest;
        unityWebRequest = UnityWebRequest.Get(url);
        yield return unityWebRequest.SendWebRequest();
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            Debug.Log(unityWebRequest.downloadHandler.text);
        }
    }

 

 

 

오디오 파일 로드

//전용 세이브 폴더 참조시에는
//$"file://{UnityEngine.Application.persistentDataPath}/Audio.mp3";
static AudioClip LoadAudioClip(string downloadLink)
{
    var fileName= downloadLink;
    if (System.IO.File.Exists(downloadLink))
    {
        downloadLink = $"file://{downloadLink}";
        fileName = System.IO.Path.GetFileNameWithoutExtension(downloadLink);
    }
    UnityWebRequest unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(downloadLink, AudioType.UNKNOWN);

    var operation = unityWebRequest.SendWebRequest();
    while (!operation.isDone)
    {
        Thread.Sleep(1);
    }
    if (unityWebRequest.isNetworkError)
    {
        Debug.LogError(unityWebRequest.error);
    }
    else
    {
        //Debug.Log("LoadAudioClipSuccess");
    }
    var clip = DownloadHandlerAudioClip.GetContent(unityWebRequest);
    clip.name = fileName;
    return clip;
}

 

 

 

 

캐시 테스트

    public string url;
    public string cookie;
    public string fileName;
    public string fileType;
    IEnumerator DownloadFile()
    {
        string filePath = $"{Application.persistentDataPath}/{fileName}";
        if ((fileType != null) && (fileType.Trim() != ""))
        {
            filePath += $".{fileType}";
        }
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
        if (string.IsNullOrWhiteSpace(cookie)==false)
        {
            unityWebRequest.SetRequestHeader("Cookie", cookie);
        }
        yield return unityWebRequest.SendWebRequest();
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            Debug.Log(unityWebRequest.downloadHandler.text);
            //File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(DownloadFile());
    }

'Unity > C#' 카테고리의 다른 글

c# MD5  (0) 2020.08.25
형변환 모음  (0) 2020.08.11
유니티 씬 계열 함수 모음  (0) 2020.07.30
posted by 모카쨩
2020. 8. 19. 16:26 Unity

 

 

 

 

 

 

 

비주얼스튜디오 2019는 여기에 있다

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe

 

 

 

 

가 아니고 사실 이렇게 경로를 지정해주면 안되고 비주얼 스튜디오 인스톨러를 이용해서 한번 더 설치해주면 저기에 알아서 비주얼 스튜디오 커뮤니티라고 뜬다

 

 

 

 

 

 

 

 

'Unity' 카테고리의 다른 글

유니티 Mask  (0) 2020.09.24
유니티 콜라보레이트 클라우드  (0) 2020.08.10
This mesh uses 'Multiple Canvas Renderers' for correct rendering.  (0) 2020.08.05
posted by 모카쨩
2020. 8. 11. 16:58 Unity/C#

 

 

일반적으로 사용하는 타입

var 변수= (타입)오브젝트;

 

가독성을 위해 간간히 쓰이는 타입, 괄호가 너무 많을때 사용함

var 변수= 오브젝트 as 타입

 

옛날방식

int 변수=int.Parse("1");

 

 

 

'Unity > C#' 카테고리의 다른 글

UnityWebRequest  (0) 2020.08.20
유니티 씬 계열 함수 모음  (0) 2020.07.30
C# 파일관련 함수들  (0) 2020.07.30
posted by 모카쨩

저사양 유저용 블로그 진입