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?

More than 5 years have passed since last update.

[Unity]"古いプロジェクトをサイトから持ってきて"エラーが出た。(UnityEngine.Component' does not contain a definition for〜)

Last updated at Posted at 2017-06-13

起こったこと

2Dのとあるゲームのプロジェクトをダウンロードした時に、「Type `UnityEngine.Component' does not contain a definition for〜」みたいなエラーが複数のスクリプトファイルからエラーが出た。 うん、コンポーネント取得してないぞゴラァ!って言われたわけです。 エラー自体は簡単に解決できるものだが、コンポーネント取得しなくても動きますよ感のあるコードだったので草が生えたわけです。

原因

Unity5より前はGetComponentしなくても動いてたらしい。だから、古いサンプルがそのような状態であっても不思議じゃない。

どのように対処したか

Unity5より前はGetComponentしなくても動くらしくて、拾ってきたプロジェクトのスクリプトはこんな感じで書かれていた。
I_am_hentai_before.cs
rigidbody2D.velocity = transform.up.normalized * speed;

Unity5より前ではこれで動いていたみたいだが、Unity5以降ではGetComponentしましょう。

I_am_hentai_after.cs
GetComponent<Rigidbody2D>().velocity = transform.up.normalized * speed;

これでここのスクリプトのエラーは消える。 他のスクリプトのエラーも原因は同じだったので、上記のようにGetComponentしたらエラーは消えた。
最終的には処理のたびにコンポーネント取得はよくないので、実際はStart関数でGetComponentした方がいいです。(このゲームの場合は)

感想

僕が初めてUnityを使ったのはUnity5からなので昔の書き方はあまり知らないが、そういうのも知っとくと昔のプロジェクト触る機会あるかもしれないし、意味はないことはない。 昔の本を見てみると、シーン遷移がLoadLevelって書いてある時代もあったなぁとか思ったり(回顧)
0
0
0

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?