Unityでシューティングゲームを作っています。
敵キャラクターが弾を打つ際に角度を指定して弾を動かしたいと思っています。
敵キャラクターを動かすスクリプトと弾を動かすスクリプトに分けて記述をしていますが
引数を渡す際にInvalidCastExceptionのエラーが発生しています。
スクリプトは以下の二つです。
弾を動かすもの↓
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy003BulletController : MonoBehaviour
{
float dx;
float dy;
public void shot(float angle,float speed){ dx = Mathf.Cos(angle) * speed; dy = Mathf.Sin(angle) * speed; } void Update(){ transform.position += new Vector3(dx, dy, 0) * Time.deltaTime; if (transform.position.x < -3 || transform.position.x > 3|| transform.position.y < -3 || transform.position.y > 3) { Destroy(gameObject); } }
}
敵を動かすもの↓
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy003Controller : MonoBehaviour
{
public Enemy003BulletController Enemy003bulletPrefab;
public void Start () { Shot(0.01f,0.01f); //ここでエラー } void Shot(float angle, float speed){ Enemy003BulletController bullet = Instantiate(Enemy003bulletPrefab, transform.position, transform.rotation); bullet.shot(angle,speed); //ここでエラー }
}
以上でコンパイルは通りますが実行時にエラーが出ています。
InvalidCastException: Specified cast is not valid.
(wrapper castclass) System.Object.__castclass_with_cache(object,intptr,intptr)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f1212ad1dec44ce7b7147976b91869c3>:0)
Enemy003Controller.Shot (System.Single angle, System.Single speed) (at Assets/Scripts/Enemy003Controller.cs:18)
Enemy003Controller.Start () (at Assets/Scripts/Enemy003Controller.cs:13)
かたのキャストができていないようで、Gettypeなどで確認したのですが、取得できる変数の型はすべてSingleとなっており、float型の変数で動かしていることについては問題が無いように思います。
なにか記述に間違いがあるのでしょうか。解決策があればご教示いただければ幸いです。

回答1件
あなたの回答
tips
プレビュー