0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#でプロパティのセッターが実行されない

Posted at

はじめに

Unity C#で詰まったので記録として

課題

Unityで配列にプロパティを実装したが、セッターのイベントが動きませんでした

/// <summary>
/// modelのデータが変更されたときに呼び出されるイベント
/// </summary>
public event Action OnValueChanged;

[SerializeField]
private bool[] grids;
/// <summary>
/// 各グリッドの状態
/// </summary>
public bool[] Grids 
{
	get { return grids; }
	set
	{
		grids = value;
		OnValueChanged?.Invoke();
	}
}

呼び出し

Grids[i] = true;

呼び出しを行うとプロパティが起動されると想定していたのですが、イベントは起動しませんでした

解決方法

配列の一要素にアクセスする場合、配列全体のプロパティは実行されないそうです
そのため、変更用のメソッドを実行してそこでイベントを発火することにしました

/// <summary>
/// グリッドの値を変更しイベントを発行する
/// </summary>
/// <param name="index"></param>
/// <param name="state"></param>
public void SetGridState(int index, bool state)
{
	// 変更がない場合は何もしない
	if (grids[index] == state) return;

	grids[index] = state;
	OnValueChanged?.Invoke();
}

おわりに

配列全体をコピーして上書きすればプロパティを実行できるかもしれません

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?