LoginSignup
8
7

More than 5 years have passed since last update.

Unity5 プログラムからスクリプトコンポーネントを追加する

Last updated at Posted at 2015-06-02

言語:C#
詰まったのでメモ。

エラーが出た例

NewBehaviourScript.cs


using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    public GameObject obj;

    void Start (){
        obj.AddComponent("Sample.cs");
    }
}

objにSample.csを追加しようと


obj.AddComponent("Sample.cs");

するとUnityからメッセージが出てくる
スクリーンショット 2015-06-02 18.49.48.png

「新しいバージョン用のスクリプトに書き換えます」的なことを言われるので
[I Made a Backup. Go Ahead!]をクリックして進む


void Start (){
    UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(obj, "Assets/NewBehaviourScript.cs (9,3)", "Sample.cs");
}

に書き換えられた

実行してみる

Component Type 'Sample.cs' not found. とエラーが出てしまった。

エラー回避

gameObject.AddComponent<コンポーネント名>();とするとうまくいく


using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    public GameObject obj;

    void Start (){
        obj.AddComponent<Sample>();
    }
}

8
7
2

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
8
7