Unityでマウスカーソルの画像を変更する方法

マウスカーソルの画像を(一時的に)変更したい場合はCursor.SetCursorを使うと実装できるみたいです。

使い方

例えば、カーソルが特定のエリアにある時にカーソル画像を変更したい場合は次のような感じです。

public class Example : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
  public Texture2D cursorTexture;

  public void OnPointerEnter(PointerEventData eventData)
  {
    Cursor.SetCursor(cursorTexture, Vector2.zero, CursorMode.Auto);
  }

  public void OnPointerExit(PointerEventData eventData)
  {
    Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
  }
}

これとUI.Buttonを組み合わせれば、ボタン上にカーソルが来た時にカーソル画像を変更したりできるみたいです。

リンク

Unity – Scripting API: Cursor.SetCursor(Texture2D,CursorMode)
https://docs.unity3d.com/ScriptReference/Cursor.SetCursor.html

TextureをPNGファイルとして保存する方法

先日、PNGファイルを読み込んでTextureとして使う方法という記事を書きましたが、逆にTextureをPNGファイルとして保存したい場合は、EncodeToPNGを使って次のような感じで実装できるみたいです。

Texture2D texture;
string path = "texture.png";
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(path, bytes);

PNGフォーマット以外にもEXRフォーマット、JPGフォーマット、TGAフォーマットに対応しているそうです。

リンク

Unity – Scripting API: ImageConversion.EncodeToPNG
https://docs.unity3d.com/ScriptReference/ImageConversion.EncodeToPNG.html

Unity – Scripting API: Windows.File.WriteAllBytes
https://docs.unity3d.com/ScriptReference/Windows.File.WriteAllBytes.html

C#でプロパティーを使ったinterfaceの使い方

C#でプロパティーを使ったinterfaceの使い方をよく忘れてしまうので、メモしておこうかなと思います。

使い方は次のような感じです。

インターフェース

public interface IExample
{
  string Name
  {
    get;
    set;
  }
}

使っているところ

using System;

public class Example : IExample
{
  string _name = "";

  public string Name
  {
    get { return _name; }
    set { _name = value; }
  }

  public Example(string name)
  {
    _name = name;
  }
}

public class TestExample
{
  static public void Main ()
  {
    IExample example = new Example("name");

    Console.WriteLine($"example.name = {example.Name}");

    example.Name = "new name";
    Console.WriteLine($"example.name = {example.Name}");
  }
}

実行結果

example.name = name
example.name = new name

何故かよく忘れてしまいます。

リンク

Interface Properties – C# Programming Guide | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties