Help us understand the problem. What is going on with this article?

Instantiate 後に任意の型にキャストする

More than 3 years have passed since last update.

Unity でプレハブを Instantiate した後、そのオブジェクトに対して何かしらの操作を加えたい、ということはよくあるのではないでしょうか。
しかし、Instantiate で返されるオブジェクトは Object 型のためそのままでは操作できません。以下のようにキャストをかける必要があります。

InstantiateTest.cs
using UnityEngine;

public class InstantiateTest : MonoBehaviour {

    [SerializeField]
    private GameObject pref;

    void Start () {
        var go = Instantiate(pref) as GameObject ;
    }  
}

インスタンス化するオブジェクトに Rigidbody をアタッチしていて Rigidbody を操作したい場合、以下のようなコードを書くかと思いますが、このままではコンパイルが通りません。

InstantiateTest.cs
using UnityEngine;

public class InstantiateTest : MonoBehaviour {

    [SerializeField]
    private GameObject pref;

    void Start () {        
        var rb = Instantiate(pref) as Rigidbody; // ここでエラー.
    }   
}

これは、 pref が GameObject 型として割り当てられているためです。これを解決する方法は2つ考えられます。

1.GameObject にキャストした後にさらに任意の型を GetComponent

InstantiateTest.cs
using UnityEngine;

public class InstantiateTest : MonoBehaviour {

    [SerializeField]
    private GameObject pref;

    void Start () {
        var rb = (Instantiate(pref) as GameObject).GetComponent<Rigidbody>();
    }   
}

2.pref の型を変換したいものにしておく

InstantiateTest.cs
using UnityEngine;

public class InstantiateTest : MonoBehaviour {

    [SerializeField]
    private Rigidbody pref;

    void Start () {
        var rb = Instantiate(pref) as Rigidbody;
    }   
}
Gok
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした