블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2737)
Unity3D (817)
Script (91)
Extensions (14)
Effect (3)
NGUI (77)
UGUI (8)
Physics (2)
Shader (36)
Math (1)
Design Pattern (2)
Xml (1)
Tips (200)
Link (22)
World (1)
AssetBundle (25)
Mecanim (2)
Plugins (70)
Trouble Shooting (68)
Encrypt (7)
LightMap (4)
Shadow (4)
Editor (8)
Crash Report (3)
Utility (9)
UnityVS (2)
Facebook SDK (2)
iTween (3)
Font (11)
Ad (14)
Photon (2)
IAP (1)
Google (8)
Android (45)
iOS (41)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-29 00:03

    // 원하는 Type을 Object로 넘겨서 시리얼라이즈 한 후, string으로 받아옴.

    // 이 값을 PlayerPrefs에 저장.

    private string ObjectToString(System.Object _cObject)

    {

        if (_cObject == null)

            return null;

        var binaryFormatter = new BinaryFormatter();

        var memoryStream = new MemoryStream();

        binaryFormatter.Serialize(memoryStream, _cObject);

        

        return Convert.ToBase64String(memoryStream.GetBuffer());

    }


    // PlayerPrefs에 저장된 값을 string에 받아와서 Object로 변환 후, 맞는 Type으로 형변환. Collection도 가능.

    // 예) List<MyClass> listValues = StringToObject(strValue) as List<MyClass>;

    private System.Object StringToObject(string _strValue)

    {

        if (true == string.IsNullOrEmpty(_strValue))

            return null;


        var binaryFormatter = new BinaryFormatter();

        var memoryStream = new MemoryStream(Convert.FromBase64String(_strValue));

        

        System.Object obj = binaryFormatter.Deserialize(memoryStream);


        return obj;

    }






출처 : http://kookiandkiki.blogspot.kr/2014/01/unity3d_432.html



이전 포스팅에서 간단한 데이터를 저장하는 법을 봤는데요,

만약에 저장할 데이터가 간단하지 않고 좀 복잡하다...라고 한다면 아래처럼 테이블을 만들어서 저장합니다.

==============================================================================

using UnityEngine;
using System.Collections;
using System.Collections.Generic;   // 리스트를 쓰기 위해 추가합니다.

public class csTest : MonoBehaviour 
{
    // 이렇게 클래스를 만들고
    [Serializable]           // 저장하기 위해서 있어야 합니다.
    public class ScoreEntry
    {
        public string name;
        public int score;
    }

    string currentPlayerName;
    int score;

    // 만든 클래스를 리스트에 담아서 관리하면 마치 테이블처럼 사용할 수 있습니다. 
    public List<ScoreEntry> highScore = new List<ScoreEntry>();

    void AddData()
    {
        // 이렇게 새로운 데이터를 추가해주고
        highScore.Add(new ScoreEntry { name = currentPlayerName, score = score });
    }

    void OnGUI()
    {
        // 이렇게 화면에 랭킹 정보를 보여주면 됩니다. 
        foreach (ScoreEntry nowScore in highScore)
        {
            GUILayout.Label(string.Format("{0} : {1:#, 0}", nowScore.name, nowScore.score));
        }
    }
}

==============================================================================

이렇게 정보를 테이블처럼 만든 후에는 BinaryFormatter를 사용해서 저장할 수 있습니다. 

BinaryFormatter는 '파라미터를 갖지 않는 생성자'를 갖는 클래스라면 어떤 클래스도 바이트 배열로 변환하고, 그것을 다시 문자열 값으로 변환할 수 있습니다. 

문자열 값으로 변환이 가능하다면 이전 포스팅에서 설명한 PlayerPrefs에 저장할 수 있게 되겠죠.

==============================================================================

using UnityEngine;
using System.Collections;
using System.Collections.Generic;   // 리스트를 쓰기 위해 추가합니다.

// BinaryFormatter를 사용하기 위해서는 반드시 아래의 네임스페이스를 추가해줘야 해요.
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class csTest : MonoBehaviour 
{
    // 이렇게 클래스를 만들고
    [Serializable]           // 저장하기 위해서 있어야 합니다.
    public class ScoreEntry
    {
        public string name;
        public int score;
    }

    // 만든 클래스를 리스트에 담아서 관리하면 마치 테이블처럼 사용할 수 있습니다. 
    public List<ScoreEntry> highScore = new List<ScoreEntry>();

    void SaveScores()
    {
        var binaryFormatter     = new BinaryFormatter();
        var memoryStream        = new MemoryStream();

        // score를 바이트 배열로 변환해서 저장합니다.
        binaryFormatter.Serialize(memoryStream, highScore);

        // 그것을 다시 한번 문자열 값으로 변환해서 
        // 'HighScore'라는 스트링 키값으로 PlayerPrefs에 저장합니다.
        PlayerPrefs.SetString("HighScore", Convert.ToBase64String(memoryStream.GetBuffer()));
    }

    void Start()
    {
        // 'HighScore' 스트링 키값으로 데이터를 가져옵니다.
        var data = PlayerPrefs.GetString("HighScore");

        if (!string.IsNullOrEmpty(data))
        {
            var binaryFormatter     = new BinaryFormatter();
            var memoryStream        = new MemoryStream(Convert.FromBase64String(data)));

            // 가져온 데이터를 바이트 배열로 변환하고
            // 사용하기 위해 다시 리스트로 캐스팅해줍니다.
            highScore       = (List<ScoreEntry>)binaryFormatter.Deserialize(memoryStream);
        }
    }
}

==============================================================================


반응형

'Unity3D > Script' 카테고리의 다른 글

OnGUI() 상에서 마우스 더블 클릭 구현  (0) 2014.11.20
LightMap 동적 로딩.  (0) 2014.10.01
Unity Serializer  (0) 2014.09.25
Simple C# Unity Serializer  (0) 2014.09.25
ClipboardHelper  (0) 2014.05.15
Posted by blueasa
, |

Unity Serializer

Unity3D/Script / 2014. 9. 25. 16:30


Link : http://whydoidoit.com/unityserializer/

반응형

'Unity3D > Script' 카테고리의 다른 글

LightMap 동적 로딩.  (0) 2014.10.01
좀 더 복잡한 데이터 저장하기  (6) 2014.09.25
Simple C# Unity Serializer  (0) 2014.09.25
ClipboardHelper  (0) 2014.05.15
유니티 코루틴 깊이 알고 재미있게 쓰기.  (0) 2014.05.09
Posted by blueasa
, |

I wrote this class to serializes common unity types into and out of a byte array. Its nothing fancy, but its handy for networking player state.

     //--- Serialize ---  
     UnitySerializer srlzr = new UnitySerializer();  
     srlzr.Serialize(new Vector3(4, 8, 6));  
     byte[] byteArray = srlzr.ByteArray;  
   
     // send byte array somewhere..  
   
     //--- Deserialize ---  
     UnitySerializer dsrlzr = new UnitySerializer(byteArray);  
     Vector3 point3 = dsrlzr.DeserializeVector3();  


It supports Vector3, Vector2 and Quaternions, as well as the common primitives and its easy enough to extend to extra types. Just be sure to deserialize the data in the same order it was serialized. Check out the Example() function at the bottom to see how it works.


 // Author: Richard Pieterse, April 2013  
   
 using UnityEngine;  
 using System.Collections.Generic;  
 using System;  
   
 public class UnitySerializer {  
   
   private List<byte> byteStream = new List<byte>();  
   private byte[] byteArray;  
   private int index = 0;  
   
   /// <summary>  
   /// Returns the stream as a Byte Array  
   /// </summary>  
   public byte[] ByteArray  
   {  
     get  
     {  
       if ( byteArray == null || byteStream.Count != byteArray.Length)  
         byteArray = byteStream.ToArray();  
   
       return byteArray;  
     }  
   }  
   
   /// <summary>  
   /// Create a new empty stream  
   /// </summary>  
   public UnitySerializer()  
   {  
   
   }  
   
   /// <summary>  
   /// Initialiaze a stream from a byte array.  
   /// Used for deserilaizing a byte array  
   /// </summary>  
   /// <param name="ByteArray"></param>  
   public UnitySerializer(byte[] ByteArray)  
   {  
     byteArray = ByteArray;  
     byteStream = new List<byte>(ByteArray);  
   }  
   
     
   
   // --- double ---  
   public void Serialize(double d)  
   {  
     byteStream.AddRange( BitConverter.GetBytes(d));  
   
   }  
   
   public double DeserializeDouble()  
   {  
     double d = BitConverter.ToDouble(ByteArray, index); index += 8;  
     return d;  
   }  
   //  
   
   // --- bool ---  
   public void Serialize(bool b)  
   {  
     byteStream.AddRange(BitConverter.GetBytes(b));  
   }  
   
   public bool DeserializeBool()  
   {  
     bool b = BitConverter.ToBoolean(ByteArray, index); index += 1;  
     return b;  
   }  
   //  
   
   // --- Vector2 ---  
   public void Serialize(Vector2 v)  
   {  
     byteStream.AddRange(GetBytes(v));  
   }  
   
   public Vector2 DeserializeVector2()  
   {  
     Vector2 vector2 = new Vector2();  
     vector2.x = BitConverter.ToSingle(ByteArray, index); index += 4;  
     vector2.y = BitConverter.ToSingle(ByteArray, index); index += 4;  
     return vector2;  
   }  
   //  
   
   // --- Vector3 ---  
   public void Serialize(Vector3 v)  
   {  
     byteStream.AddRange(GetBytes(v));  
   }  
   
   public Vector3 DeserializeVector3()  
   {  
     Vector3 vector3 = new Vector3();  
     vector3.x = BitConverter.ToSingle(ByteArray, index); index += 4;  
     vector3.y = BitConverter.ToSingle(ByteArray, index); index += 4;  
     vector3.z = BitConverter.ToSingle(ByteArray, index); index += 4;  
     return vector3;  
   }  
   //  
   
   // --- Type ---  
   public void Serialize(System.Type t)  
   {  
     // serialize type as string  
     string typeStr = t.ToString();  
     Serialize(typeStr);  
   }  
   
   public Type DeserializeType()  
   {  
     // type stored as string  
     string typeStr = DeserializeString();  
     return Type.GetType(typeStr); ;  
   }  
   //  
   
   // --- String ---  
   public void Serialize(string s)  
   {  
     // add the length as a header  
     byteStream.AddRange(BitConverter.GetBytes(s.Length));  
     foreach (char c in s)  
       byteStream.Add((byte)c);  
   }  
   
   public string DeserializeString()  
   {  
     int length = BitConverter.ToInt32(ByteArray, index); index += 4;  
     string s = "";  
     for (int i = 0; i < length; i++)  
     {  
       s += (char)ByteArray[index];  
       index++;  
     }  
   
     return s;  
   }  
   //  
   
   // --- byte[] ---  
   public void Serialize(byte[] b)  
   {  
     // add the length as a header  
     byteStream.AddRange(BitConverter.GetBytes(b.Length));  
     byteStream.AddRange(b);  
   }  
   
   public byte[] DeserializeByteArray()  
   {  
     int length = BitConverter.ToInt32(ByteArray, index); index += 4;  
     byte[] bytes = new byte[length];  
     for (int i = 0; i < length; i++)  
     {  
       bytes[i] = ByteArray[index];  
       index++;  
     }  
      
     return bytes;  
   }  
   //  
   
   // --- Quaternion ---  
   public void Serialize(Quaternion q)  
   {  
     byteStream.AddRange(GetBytes(q));  
   }  
   
   public Quaternion DeserializeQuaternion()  
   {  
     Quaternion quat = new Quaternion();  
     quat.x = BitConverter.ToSingle(ByteArray, index); index += 4;  
     quat.y = BitConverter.ToSingle(ByteArray, index); index += 4;  
     quat.z = BitConverter.ToSingle(ByteArray, index); index += 4;  
     quat.w = BitConverter.ToSingle(ByteArray, index); index += 4;  
     return quat;  
   }  
   //  
   
   // --- float ---  
   public void Serialize(float f)  
   {  
     byteStream.AddRange(BitConverter.GetBytes(f));  
   }  
   
   public float DeserializeFloat()  
   {  
     float f = BitConverter.ToSingle(ByteArray, index); index += 4;  
     return f;  
   }  
   //  
   
   // --- int ---  
   public void Serialize(int i)  
   {  
     byteStream.AddRange(BitConverter.GetBytes(i));  
   }  
   
   public int DeserializeInt()  
   {  
     int i = BitConverter.ToInt32(ByteArray, index); index += 4;  
     return i;  
   }  
   //  
   
   // --- internal ----  
   Vector3 DeserializeVector3(byte[] bytes, ref int index)  
   {  
     Vector3 vector3 = new Vector3();  
     vector3.x = BitConverter.ToSingle(bytes, index); index += 4;  
     vector3.y = BitConverter.ToSingle(bytes, index); index += 4;  
     vector3.z = BitConverter.ToSingle(bytes, index); index += 4;  
   
     return vector3;  
   }  
   
   Quaternion DeserializeQuaternion(byte[] bytes, ref int index)  
   {  
     Quaternion quat = new Quaternion();  
     quat.x = BitConverter.ToSingle(bytes, index); index += 4;  
     quat.y = BitConverter.ToSingle(bytes, index); index += 4;  
     quat.z = BitConverter.ToSingle(bytes, index); index += 4;  
     quat.w = BitConverter.ToSingle(bytes, index); index += 4;  
     return quat;  
   }  
   
   byte[] GetBytes(Vector2 v)  
   {  
     List<byte> bytes = new List<byte>(8);  
     bytes.AddRange(BitConverter.GetBytes(v.x));  
     bytes.AddRange(BitConverter.GetBytes(v.y));  
     return bytes.ToArray();  
   }  
   
   byte[] GetBytes(Vector3 v)  
   {  
     List<byte> bytes = new List<byte>(12);  
     bytes.AddRange(BitConverter.GetBytes(v.x));  
     bytes.AddRange(BitConverter.GetBytes(v.y));  
     bytes.AddRange(BitConverter.GetBytes(v.z));  
     return bytes.ToArray();  
   }  
   
   byte[] GetBytes(Quaternion q)  
   {  
     List<byte> bytes = new List<byte>(16);  
     bytes.AddRange(BitConverter.GetBytes(q.x));  
     bytes.AddRange(BitConverter.GetBytes(q.y));  
     bytes.AddRange(BitConverter.GetBytes(q.z));  
     bytes.AddRange(BitConverter.GetBytes(q.w));  
     return bytes.ToArray();  
   }  
   
   public static void Example()  
   {  
     //  
     Debug.Log("--- UnitySerializer Example ---");  
     Vector2 point      = UnityEngine.Random.insideUnitCircle;  
     Vector3 position    = UnityEngine.Random.onUnitSphere;  
     Quaternion quaternion  = UnityEngine.Random.rotation;  
     float f         = UnityEngine.Random.value;  
     int i          = UnityEngine.Random.Range(0, 10000);  
     double d        = (double)UnityEngine.Random.Range(0, 10000);  
     string s        = "Brundle Fly";  
     bool b         = UnityEngine.Random.value < 0.5f ? true : false;  
     System.Type type    = typeof(UnitySerializer);  
   
     //  
     Debug.Log("--- Before ---");  
     Debug.Log(point + " " + position + " " + quaternion + " " + f + " " + d + " " + s + " " + b + " " + type);  
   
     //  
     Debug.Log("--- Serialize ---");  
     UnitySerializer us = new UnitySerializer();  
     us.Serialize(point);  
     us.Serialize(position);  
     us.Serialize(quaternion);  
     us.Serialize(f);  
     us.Serialize(i);  
     us.Serialize(d);  
     us.Serialize(s);  
     us.Serialize(b);  
     us.Serialize(type);  
     byte[] byteArray = us.ByteArray;  
       
     // the array must be deserialized in the same order as it was serialized  
     Debug.Log("--- Deserialize ---");  
     UnitySerializer uds   = new UnitySerializer(byteArray);  
     Vector2 point2     = uds.DeserializeVector2();  
     Vector3 position2    = uds.DeserializeVector3();  
     Quaternion quaternion2 = uds.DeserializeQuaternion();  
     float f2        = uds.DeserializeFloat();  
     int i2         = uds.DeserializeInt();  
     double d2        = uds.DeserializeDouble();  
     string s2        = uds.DeserializeString();  
     bool b2         = uds.DeserializeBool();  
     System.Type type2    = uds.DeserializeType();  
   
     //  
     Debug.Log("--- After ---");  
     Debug.Log(point2 + " " + position2 + " " + quaternion2 + " " + f2 + " " + d2 + " " + s2 + " " + b2 + " " + type2);  
   }  
 }  
   



출처 : http://deciduousgames.blogspot.kr/2013/04/unity-serializer.html

반응형

'Unity3D > Script' 카테고리의 다른 글

좀 더 복잡한 데이터 저장하기  (6) 2014.09.25
Unity Serializer  (0) 2014.09.25
ClipboardHelper  (0) 2014.05.15
유니티 코루틴 깊이 알고 재미있게 쓰기.  (0) 2014.05.09
ScreenWipe CrossFade with C#  (0) 2014.04.22
Posted by blueasa
, |

ClipboardHelper

Unity3D/Script / 2014. 5. 15. 02:08

출처 : http://answers.unity3d.com/questions/266244/how-can-i-add-copypaste-clipboard-support-to-my-ga.html



  1. // C#
  2. // ClipboardHelper.cs
  3. using UnityEngine;
  4. using System;
  5. using System.Reflection;
  6.  
  7. public class ClipboardHelper
  8. {
  9. private static PropertyInfo m_systemCopyBufferProperty = null;
  10. private static PropertyInfo GetSystemCopyBufferProperty()
  11. {
  12. if (m_systemCopyBufferProperty == null)
  13. {
  14. Type T = typeof(GUIUtility);
  15. m_systemCopyBufferProperty = T.GetProperty("systemCopyBuffer", BindingFlags.Static | BindingFlags.NonPublic);
  16. if (m_systemCopyBufferProperty == null)
  17. throw new Exception("Can't access internal member 'GUIUtility.systemCopyBuffer' it may have been removed / renamed");
  18. }
  19. return m_systemCopyBufferProperty;
  20. }
  21. public static string clipBoard
  22. {
  23. get
  24. {
  25. PropertyInfo P = GetSystemCopyBufferProperty();
  26. return (string)P.GetValue(null,null);
  27. }
  28. set
  29. {
  30. PropertyInfo P = GetSystemCopyBufferProperty();
  31. P.SetValue(null,value,null);
  32. }
  33. }
  34. }


반응형

'Unity3D > Script' 카테고리의 다른 글

Unity Serializer  (0) 2014.09.25
Simple C# Unity Serializer  (0) 2014.09.25
유니티 코루틴 깊이 알고 재미있게 쓰기.  (0) 2014.05.09
ScreenWipe CrossFade with C#  (0) 2014.04.22
A simple cross fade shader for Unity  (0) 2014.04.22
Posted by blueasa
, |


링크 : http://www.slideshare.net/MrDustinLee/ss-33346625

반응형

'Unity3D > Script' 카테고리의 다른 글

Simple C# Unity Serializer  (0) 2014.09.25
ClipboardHelper  (0) 2014.05.15
ScreenWipe CrossFade with C#  (0) 2014.04.22
A simple cross fade shader for Unity  (0) 2014.04.22
어플을 내렸을때, 어플을 종료할때의 처리  (3) 2014.04.04
Posted by blueasa
, |




ScreenWipe_For_CSharp.zip





참조 : http://wiki.unity3d.com/index.php?title=CrossFade


출처 : http://answers.unity3d.com/questions/166898/screenwipe-crossfade-with-c.html

반응형

'Unity3D > Script' 카테고리의 다른 글

ClipboardHelper  (0) 2014.05.15
유니티 코루틴 깊이 알고 재미있게 쓰기.  (0) 2014.05.09
A simple cross fade shader for Unity  (0) 2014.04.22
어플을 내렸을때, 어플을 종료할때의 처리  (3) 2014.04.04
Unity Singleton  (0) 2014.03.24
Posted by blueasa
, |

The other day I was putting some polish to Deathfire‘s character generation and we wanted to fade character portraits from one to another when the player makes his selections. Unlike hard cuts, cross fades simply add a bit of elegance to the program that we did not want to miss.

I went through Unity’s documentation and very quickly came across its Material.Lerp function. Just what I needed, I thought, but after a quick implementation it turned out it didn’t do what I had had in mind. I had not read the function description properly, because what it does, is blend between the parameters of two materials and not the actual image the material creates. Since I am working with a texture atlas, this gave me a cool scrolling effect as my material lerped from one end of the atlas to the other but not the kind of cross fade I had had in mind.

It turns out that Unity doesn’t really have the functionality, so I dug a bit deeper and found Ellen’s approach to blending textures. A quick check of her sources showed me that it still did not do what I wanted, but it gave me a good basis to start from as I began writing my own implement of a simple cross fader.

It all starts with the shader itself, which takes two textures without a normal map and renders them on top of another. A variable tells the shader how transparent the top texture should be so we can adjust it on the fly and gradually blend from the first texture to the second. The key feature for my approach was that the shader uses UV coordinates for each of the textures to allow me to use the shader with a texture atlas.

Shader "CrossFade"
{
  Properties
  {
    _Blend ( "Blend", Range ( 0, 1 ) ) = 0.5
    _Color ( "Main Color", Color ) = ( 1, 1, 1, 1 )
    _MainTex ( "Texture 1", 2D ) = "white" {}
    _Texture2 ( "Texture 2", 2D ) = ""
  }

  SubShader
  {
    Tags { "RenderType"="Opaque" }
    LOD 300
    Pass
    {
      SetTexture[_MainTex]
      SetTexture[_Texture2]
      {
        ConstantColor ( 0, 0, 0, [_Blend] )
        Combine texture Lerp( constant ) previous
      }    
    }
  
    CGPROGRAM
    #pragma surface surf Lambert
    
    sampler2D _MainTex;
    sampler2D _Texture2;
    fixed4 _Color;
    float _Blend;
    
    struct Input
    {
      float2 uv_MainTex;
      float2 uv_Texture2;
    };
    
    void surf ( Input IN, inout SurfaceOutput o )
    {
      fixed4 t1  = tex2D( _MainTex, IN.uv_MainTex ) * _Color;
      fixed4 t2  = tex2D ( _Texture2, IN.uv_Texture2 ) * _Color;
      o.Albedo  = lerp( t1, t2, _Blend );
    }
    ENDCG
  }
  FallBack "Diffuse"
}

The second part of the implementation is the C# script that will drive the actual cross fade. It is pretty straight-forward and consists of an initialization function Start(), an Update() function that is called periodically and adjusts the blend factor for the second texture until the fade is complete. And then, of course, there is a function CrossFadeTo() that you call to set up the respective cross fade.

using UnityEngine;
using System.Collections;

public class CrossFade : MonoBehaviour
{
  private Texture    newTexture;
  private Vector2    newOffset;
  private Vector2    newTiling;
  
  public  float    BlendSpeed = 3.0f;
  
  private bool    trigger = false;
  private float    fader = 0f;
  
  void Start ()
  {
    renderer.material.SetFloat( "_Blend", 0f );
  }
  
  void Update ()
  {
    if ( true == trigger )
    {
      fader += Time.deltaTime * BlendSpeed;
      
      renderer.material.SetFloat( "_Blend", fader );
      
      if ( fader >= 1.0f )
      {
        trigger = false;
        fader = 0f;
        
        renderer.material.SetTexture ("_MainTex", newTexture );
        renderer.material.SetTextureOffset ( "_MainTex", newOffset );
        renderer.material.SetTextureScale ( "_MainTex", newTiling );
        renderer.material.SetFloat( "_Blend", 0f );
      }
    }
  }
  
  public void CrossFadeTo( Texture curTexture, Vector2 offset, Vector2 tiling )
  {
    newOffset = offset;
    newTiling = tiling;
    newTexture = curTexture;
    renderer.material.SetTexture( "_Texture2", curTexture );
    renderer.material.SetTextureOffset ( "_Texture2", newOffset );
    renderer.material.SetTextureScale ( "_Texture2", newTiling );
    trigger = true;
  }
}

The script also contains a public variable called BlendSpeed, which is used to determine how quickly the fade will occur. Smaller numbers will result in slower fades, while larger numbers create more rapid cross fades.

In order to use these scripts, all you have to do is add the shader and the script to your Unity project. Attach the C# script to the object you want to perform the cross fade and then from your application simply call CrossFadeTo() with proper texture parameters to make it happen. That is all there really is to it.


  CrossFade bt = gameObject.GetComponent();
  bt.CrossFadeTo( myTexture, myUVOffset, myScale );

I hope some of you may find this little script useful.

- See more at: http://guidohenkel.com/2013/04/a-simple-cross-fade-shader-for-unity/#comment-125802



출처 : http://networkedblogs.com/Kx9ce

반응형
Posted by blueasa
, |

어플리케이션의 스테이트에 따라서 특정한 처리가 요구될 경우가 있습니다.

이를 위해 안드로이드. iOS 양쪽 모두 통용되는 메소드를 지원하고 있습니다. 

 

OnApplicationPause(bool pause) : 홈키로 어플을 내려 pause 상태로 만들었을 때의 처리

OnApplicationQuit() : 어플을 종료할 때의 처리

 

메소드의 이름만 보면, 안드로이드 쪽에 가깝군요. 하지만 Unity3D는 여러가지 면에서 iOS를 더 사랑하는 것 같습니다.

(푸시 지원 해주는 것만 봐도...) 간략한 예제를 통해서 어떤 식으로 쓰이게 되는지 알아보도록 하겠습니다.

 

 

1) OnApplicationPause

 

bool bPaused = false;  // 어플리케이션이 내려진 상태인지 아닌지의 스테이트를 저장하기 위한 변수

 

void OnApplicationPause(bool pause)

{

  if (pause)

  {

    bPaused = true;

    // todo : 어플리케이션을 내리는 순간에 처리할 행동들 /

  }

  else

  {

    if (bPaused)

    {

      bPaused = false;

      //todo : 내려놓은 어플리케이션을 다시 올리는 순간에 처리할 행동들 

    }

  }

 

 

2) OnApplicationQuit

 

void OnApplicationQuit()

{

  // todo : 어플리케이션을 종료하는 순간에 처리할 행동들

}



출처] [Unity3D] 어플을 내렸을때, 어플을 종료할때의 처리|작성자 베르제


반응형

'Unity3D > Script' 카테고리의 다른 글

ScreenWipe CrossFade with C#  (0) 2014.04.22
A simple cross fade shader for Unity  (0) 2014.04.22
Unity Singleton  (0) 2014.03.24
Platform Dependent Compilation  (0) 2014.03.11
Generic Based Singleton for MonoBehaviours完全版(?)  (0) 2014.03.05
Posted by blueasa
, |

Unity Singleton

Unity3D/Script / 2014. 3. 24. 18:36
using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    protected static bool m_bDontDestroyOnLoad = true;
    
    private static bool m_bApplicationQuit = false;
    private static object InstanceLocker = new object();

    private static T m_Instance = null;
    public static T Instance
    {
        get
        {
            if (true == m_bApplicationQuit)
                return null;

            lock (InstanceLocker)
            {
                // Instance requiered for the first time, we look for it
                if (null == m_Instance)
                {
                    T instance = GameObject.FindObjectOfType(typeof(T)) as T;

                    // Object not found, we create a temporary one
                    if (instance == null)
                    {
                        instance = new GameObject(typeof(T).ToString()).AddComponent<T>();

                        // Problem during the creation, this should not happen
                        if (instance == null)
                        {
                            Debug.LogError("Problem during the creation of " + typeof(T).ToString());
                        }
                    }

                    if (instance != null)
                    {
                        Initialize(instance);
                    }
                }

                return m_Instance;
            }
        }
    }

    private static void Initialize(T instance)
    {
        if (m_Instance == null)
        {
            var startTime = System.DateTime.Now;
            m_Instance = instance;

            // 씬 전환 시, 삭제시킬 싱글톤은 부모 객체에 안붙이도록..
            // 싱글톤 시작 시, m_bDontDestroyOnLoad 셋팅 필요.
            if (true == m_bDontDestroyOnLoad)
            {
                GameObject goRoot = GameObject.Find("Singletons") as GameObject;
                if (null == goRoot)
                {
                    goRoot = new GameObject("Singletons");
                    // DontDestroyOnLoad() 등록은 하위 상속받는 쪽에서 하도록 하는 게 나을까?
                    DontDestroyOnLoad(goRoot);
                }
                m_Instance.transform.parent = goRoot.transform;
            }

            m_Instance.OnInitialize();
            var period = System.DateTime.Now - startTime;
            if (period.TotalSeconds > 1.0f)
            {
                var name = m_Instance.ToString();
                Debug.LogWarning("Profile Warnning. Singletion {" + name + "} too long init time : " 
                                 + period.TotalSeconds.ToString("F") + "Seconds");
            }
        }
        else if (m_Instance != instance)
        {
            DestroyImmediate(instance.gameObject);
        }
    }

    private static void Destroyed(T instance)
    {
        if (m_Instance == instance)
        {
            m_Instance.OnFinalize();
            m_Instance = null;
        }
    }

    public void CreateSingleton() { }
    // [Warning] GameObject에 Component로 미리 등록된 상태에서는 OnInitialize() 호출 안됨.
    public virtual void OnInitialize() { }
    // [Warning] GameObject에 Component로 미리 등록된 상태에서는 OnFinalize() 호출 안됨.
    public virtual void OnFinalize() { }
    protected virtual void CheckDontDestroyOnLoad() { }

    private void Awake()
    {
        Initialize(this as T);
    }

    void OnDestroy()
    {
        Destroyed(this as T);
    }

    private void OnApplicationQuit()
    {
        m_bApplicationQuit = true;
        Destroyed(this as T);
    }
}


반응형
Posted by blueasa
, |

Platform Dependent Compilation

Unity includes a feature named "Platform Dependent Compilation". This consists of some preprocessor directives that let you partition your scripts to compile and execute a section of code exclusively for one of the supported platforms.

Furthermore, you can run this code within the Editor, so you can compile the code specifically for your mobile/console and test it in the Editor!

Platform Defines

The platform defines that Unity supports for your scripts are:

UNITY_EDITORDefine for calling Unity Editor scripts from your game code.
UNITY_STANDALONE_OSXPlatform define for compiling/executing code specifically for Mac OS (This includes Universal, PPC and Intel architectures).
UNITY_DASHBOARD_WIDGETPlatform define when creating code for Mac OS dashboard widgets.
UNITY_STANDALONE_WINUse this when you want to compile/execute code for Windows stand alone applications.
UNITY_STANDALONE_LINUXUse this when you want to compile/execute code for Linux stand alone applications.
UNITY_STANDALONEUse this to compile/execute code for any standalone platform (Mac, Windows or Linux).
UNITY_WEBPLAYERPlatform define for web player content (this includes Windows and Mac Web player executables).
UNITY_WIIPlatform define for compiling/executing code for the Wii console.
UNITY_IPHONEPlatform define for compiling/executing code for the iPhone platform.
UNITY_ANDROIDPlatform define for the Android platform.
UNITY_PS3Platform define for running PlayStation 3 code.
UNITY_XBOX360Platform define for executing Xbox 360 code.
UNITY_NACLPlatform define when compiling code for Google native client (this will be set additionally to UNITY_WEBPLAYER).
UNITY_FLASHPlatform define when compiling code for Adobe Flash.
UNITY_BLACKBERRYPlatform define for a Blackberry10 device.
UNITY_WP8Platform define for Windows Phone 8.
UNITY_METROPlatform define for Windows Store Apps (additionally NETFX_CORE is defined when compiling C# files against .NET Core).
UNITY_WINRTEquivalent to UNITY_WP8 | UNITY_METRO

Also you can compile code selectively depending on the version of the engine you are working on. Currently the supported ones are:

UNITY_2_6Platform define for the major version of Unity 2.6.
UNITY_2_6_1Platform define for specific version 1 from the major release 2.6.
UNITY_3_0Platform define for the major version of Unity 3.0.
UNITY_3_0_0Platform define for the specific version 0 of Unity 3.0.
UNITY_3_1Platform define for major version of Unity 3.1.
UNITY_3_2Platform define for major version of Unity 3.2.
UNITY_3_3Platform define for major version of Unity 3.3.
UNITY_3_4Platform define for major version of Unity 3.4.
UNITY_3_5Platform define for major version of Unity 3.5.
UNITY_4_0Platform define for major version of Unity 4.0.
UNITY_4_0_1Platform define for major version of Unity 4.0.1.
UNITY_4_1Platform define for major version of Unity 4.1.
UNITY_4_2Platform define for major version of Unity 4.2.

Note: For versions before 2.6.0 there are no platform defines as this feature was first introduced in that version.

Testing precompiled code.

We are going to show a small example of how to use the precompiled code. This will simply print a message that depends on the platform you have selected to build your target.

First of all, select the platform you want to test your code against by clicking on File -> Build Settings. This will bring the build settings window to select your target platform.


Build Settings window with the WebPlayer Selected as Target platform.

Select the platform you want to test your precompiled code against and press the Switch Editor button to tell Unity which platform you are targeting.

Create a script and copy/paste this code:-

// JS
function Awake() {
  #if UNITY_EDITOR
    Debug.Log("Unity Editor");
  #endif

  #if UNITY_IPHONE
    Debug.Log("Iphone");
  #endif

  #if UNITY_STANDALONE_OSX
    Debug.Log("Stand Alone OSX");
  #endif

  #if UNITY_STANDALONE_WIN
    Debug.Log("Stand Alone Windows");
  #endif	
}


// C#
using UnityEngine;
using System.Collections;

public class PlatformDefines : MonoBehaviour {
  void Start () {

    #if UNITY_EDITOR
      Debug.Log("Unity Editor");
    #endif

    #if UNITY_IPHONE
      Debug.Log("Iphone");
    #endif

    #if UNITY_STANDALONE_OSX
	Debug.Log("Stand Alone OSX");
    #endif

    #if UNITY_STANDALONE_WIN
      Debug.Log("Stand Alone Windows");
    #endif

  }			   
}


// Boo
import UnityEngine

class PlatformDefines (MonoBehaviour): 

	def Start ():
		ifdef UNITY_EDITOR:
			Debug.Log("Unity Editor")

		ifdef UNITY_IPHONE:
			Debug.Log("IPhone")

		ifdef UNITY_STANDALONE_OSX:
			Debug.Log("Stand Alone OSX")

		ifdef not UNITY_IPHONE:
			Debug.Log("not an iPhone")

Then, depending on which platform you selected, one of the messages will get printed on the Unity console when you press play.

Note that in c# you can use a CONDITIONAL attribute which is a more clean, less error-prone way of stripping out functions, see http://msdn.microsoft.com/en-us/library/4xssyw96.aspx.

In addition to the basic #if compiler directive, you can also use a multiway test in C# and JavaScript:-

#if UNITY_EDITOR
    Debug.Log("Unity Editor");
#elif UNITY_IPHONE
    Debug.Log("Unity iPhone");
#else
    Debug.Log("Any other platform");
#endif

However, Boo currently supports only the ifdef directive.

Platform Custom Defines

It is also possible to add to the built-in selection of defines by supplying your own. In the Other Settings panel of the Player Settings, you will see the Scripting Define Symbols textbox.

Here, you can enter the names of the symbols you want to define for that particular platform, separated by semicolons. These symbols can then be used as the conditions for #if directives just like the built-in ones.

Global Custom Defines

You can define your own preprocessor directives to control which code gets included when compiling. To do this you must add a text file with the extra directives to the "Assets/" folder. The name of the file depends on the language you are using, and the extension is .rsp:

C#<Project Path>/Assets/smcs.rsp
C# - Editor Scripts<Project Path>/Assets/gmcs.rsp
UnityScript<Project Path>/Assets/us.rsp
Boo<Project Path>/Assets/boo.rsp

As an example, if you include the single line "-define:UNITY_DEBUG" in your smcs.rsp file the define UNITY_DEBUG will exist as a global define for C# scripts, except for Editor scripts.

Every time you make changes to .rsp files you will need to recompile for them to be effective. You can do this by updating or reimporting a single script (.js, .cs or .boo) file.

If you want to modify only global defines, you should use Scripting Define Symbols in Player Settings, because this will cover all the compilers. If you choose the .rsp files instead, you'll have to provide one file for every compiler Unity uses, and you won't know when one or another compiler is used.

The use of the .rsp files is described in the help section of the smcs application which is included in the Editor installation folder. You can get more information by running "smcs -help". Also, bear in mind the .rsp file needs to match the compiler being invoked. For example, when targeting the web player, smcs is used with smcs.rsp; when targeting standalone players, gmcs is used with gmcs.rsp; when targeting MS compiler, csc is used with csc.rsp; and so on.


출처 : https://docs.unity3d.com/Documentation/Manual/PlatformDependentCompilation.html

반응형

'Unity3D > Script' 카테고리의 다른 글

어플을 내렸을때, 어플을 종료할때의 처리  (3) 2014.04.04
Unity Singleton  (0) 2014.03.24
Generic Based Singleton for MonoBehaviours完全版(?)  (0) 2014.03.05
Singleton  (0) 2014.03.05
Serializable, NonSerialized  (0) 2013.07.30
Posted by blueasa
, |