Unity-C#

 2024.07.07 unityC#  
 2024.05.15 unityC#  
 2024.05.15 unityC#  
 2022.11.06 unityC#  
 2022.11.06 unityC#  
 2022.11.06 unityC#  
 2022.11.06 unityC#  
 2022.11.06 unityC#  
 2022.08.16 spritekit  

Delegate


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

public class TestDelegate : MonoBehaviour
 {
public delegate void DelegateType();
  //delegateの型名を宣言
 voidを指定しているから、void型の関数か登録できない。
 public DelegateType del; //delegate名を宣言
  void Start()
  {
//delegateに関数を登録 関数の後の()は必要ない
   del = DisplayText;
//delgateを発動 登録されている関数が呼ばれる
   del();
 }
//Delegateに入れる関数
 public void DisplayText()
{
 Debug.Log("DisplayTextが呼ばれました");
 }
}
delegateの型を宣言する時にint型を指定してあげれば
int型を返す関数を入れることができる。
//delegateの型名を宣言
public delegate int DelegateType(); 
宣言したdelegate型と全く同じ型のメソッドしか登録できない
////////////////////////////////////
//Sphere側で関数を登録
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class SphereScript : MonoBehaviour
{
public delegate void TimeUp(); 
 //関数を登録できる型を作成
 public TimeUp timeUp; 
//関数を登録できる変数を宣言 
  void Start()
{
  Invoke("StartChange", 2.0f); 
 //2秒後にStartChangeを実行
 } 
void StartChange()
{
 timeUp(); //timeUpを実行
    }
}
//デリゲートを使うことで、Cube側(GameManager.cs)で、
//他のスクリプトを管理。
//______________
//Cube側で関数を登録
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class GameManager : MonoBehaviour
{
public SphereScript sphereScript; 
 //SphereScriptを取得するための変数
void Start()
{
sphereScript.timeUp += ChangeColor;
  //timeUpに関数:ChangeColorを登録
} 
public void ChangeColor() 
 //timeUpが実行されると、ChangeColorも実行される
 {
GetComponent().material.color = Color.blue;
 }
}
//////////////////////////////////////////