Invoke

確認済のバージョン: 4.2

-

難易度: 初級

Invoke 関数を使うと関数を呼び出すタイミングを遅らせることができます。ここでは、Unity スクリプトの Invoke、InvokeRepeating、CancelInvoke 関数の使い方を学びます。

Invoke

初級 Scripting

InvokeScript

Code snippet

using UnityEngine;
using System.Collections;

public class InvokeScript : MonoBehaviour 
{
    public GameObject target;
    
    
    void Start()
    {
        Invoke ("SpawnObject", 2);
    }
    
    void SpawnObject()
    {
        Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
    }
}
#pragma strict

var target : GameObject;
    
    
function Start()
{
    Invoke ("SpawnObject", 2);
}
    
function SpawnObject()
{
    Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
}
import UnityEngine
import System.Collections


public class InvokeScript(MonoBehaviour):

    public target as GameObject

    
    
    private def Start():
        Invoke('SpawnObject', 2)

    
    private def SpawnObject():
        Instantiate(target, Vector3(0, 2, 0), Quaternion.identity)

InvokeRepeating

Code snippet

using UnityEngine;
using System.Collections;

public class InvokeRepeating : MonoBehaviour 
{
    public GameObject target;
    
    
    void Start()
    {
        InvokeRepeating("SpawnObject", 2, 1);
    }
    
    void SpawnObject()
    {
        float x = Random.Range(-2.0f, 2.0f);
        float z = Random.Range(-2.0f, 2.0f);
        Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
    }
}
#pragma strict

var target : GameObject;


function Start()
{
    InvokeRepeating("SpawnObject", 2, 1);
}

function SpawnObject()
{
    var x : float = Random.Range(-2.0f, 2.0f);
    var z : float = Random.Range(-2.0f, 2.0f);
    Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
}
import UnityEngine
import System.Collections


public class InvokeRepeating(MonoBehaviour):

    public target as GameObject

    
    
    private def Start():
        InvokeRepeating('SpawnObject', 2, 1)

    
    private def SpawnObject():
        x as single = Random.Range(-2.0F, 2.0F)
        z as single = Random.Range(-2.0F, 2.0F)
        Instantiate(target, Vector3(x, 2, z), Quaternion.identity)

関連するチュートリアル