みなさま、初めまして!新人のSu3です。
現在某新作アプリの開発に携わらせていただいております。
新しい環境や情報に目眩を覚えながら、難しさとやりがいの両面を持ちこれからも研鑽を積んで参りますので、何卒よろしくお願いいたします<(_ _)>
今回はUnityを触る上で恐らく大半の方が触るであろうtutorialから気になった点を一つあげてみたいと思います!
現在のUnityのメジャーバージョンは5になっているんですが、tutorial動画は4のまま・・・(動画下のScriptくらいは直せよ)
下記は「スペースシューター」Moving the playerのScriptです
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
using UnityEngine; using System.Collections; [System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; } public class PlayerController : MonoBehaviour { public float speed; public float tilt; public Boundary boundary; void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); rigidbody.velocity = movement * speed; rigidbody.position = new Vector3 ( Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax) ); rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt); } } |
この通りにやってもエラーを吐いてしまいます・・・
Unity5のアップグレードマニュアルには
In Unity 5 and later we can no longer access components using their “shorthand helper references” such as “rigidbody.” and we must access them directly using “GetComponent”.
要約すると「rigidbody」へは「GetComponent」で指定して直接アクセスしないといけませんよ〜てことです。
1234 public class PlayerControllerDemo : MonoBehaviour{private Rigidbody rb;
上記をクラスの先頭に記述して・・・
1234 void Start (){rb = GetComponent<Rigidbody> ();}
これで後は「rigidbody」の部分を上の「rb」に差し替えてあげれば大丈夫です!
こんな感じです!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControllerDemo : MonoBehaviour { private Rigidbody rb; [System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; } public float speed; public float tilt; public Boundary boundary; void Start () { rb = GetComponent<Rigidbody> (); } void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical); rb.velocity = movement * speed; rb.position = new Vector3 ( Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax) ); rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt); } } |
すごく初歩的な内容ですがお役に立てたら嬉しいです!
また次回もお楽しみに・・・
人に見せるプログラムであるならコメントを記載すると更に良いです!
//でコメント記載できるので活用しましょう!
更に///を打つとサマリーも記載できるので各メソッドの説明なども記載しとくと自分のためにはもちろん、チームのためにもなるのでファイトです!!
publicの多用も禁物です>_<
ご指摘ありがとうございます!
精進します><