[英]Object reference not set to instance of an object Unity3D c#
这是播放器脚本:
public class player
{ public projectile pro;
pro = GetComponent<projectile>();
void Update()
{
GameObject go = GameObject.Find("enemy");
Transform playerTransform = go.transform;
Vector3 posi = playerTransform.position;
pro.Target = posi; // getting error here
Instantiate(bulletprefab, position, Quaternion.identity);
}
}
这是Projectile脚本:要求:获取Target在Projectile中的更新位置,但是由于从Start()
调用了projectileMotion()
方法,并且我希望在Player
调用Instantiate
时的目标当前位置,以便在Target_Distance
适当地计算Target_Distance
射弹类,但是看起来像是从Vector3到_pro.Target的赋值,后者仅是vector3。 我能解决这个问题吗?
public class projectile : MonoBehaviour
{
public Vector3 Target;
public GameObject bulletprefab;
public float firingAngle = 45.0f;
public float gravity = 9.8f;
public Transform Projectile;
private Transform myTransform;
void Awake()
{
myTransform = transform;
}
void Start()
{ myTransform.LookAt(Target);
StartCoroutine (ProjectileMotion ());
}
IEnumerator ProjectileMotion()
{
yield return new WaitForSeconds(0.25f);
Projectile.position = myTransform.position + new Vector3(0, 0.0f, 0);
// Calculating distance to target
float target_Distance = Vector3.Distance(Projectile.position, Target );
Debug.Log ("realUPDATEDOR not" + Target);
float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle* Mathf.Deg2Rad) / gravity);
// X Y componenent of the velocity
float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);
// flight time since depends on horizontal component of velocity
float flightDuration = target_Distance / Vx;
// projectile rotated at target
Projectile.rotation = Quaternion.LookRotation(Target - Projectile.position);
float elapse_time = 0;
while (elapse_time < flightDuration) //looping and incrementing elapsed time
{
Projectile.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);
elapse_time += Time.deltaTime;
yield return null;
}
}
}
目标存在于Projectile类中,并且仅是Vector3,如何解决此错误?
您获得对“弹丸”脚本的引用的代码将无法工作。
变化:
public projectile pro;
pro = GetComponent<projectile>();
像这样:
public projectile pro;
void Start()
{
pro = GetComponent<projectile>();
}
另外建议您可能要减少GameObject.Find在更新函数中的使用,原因是其成本高昂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.