【问题标题】:Cannot convert type `UnityEngine.Rigidbody' to `ProjectileController' via a built-in conversion无法通过内置转换将类型“UnityEngine.Rigidbody”转换为“ProjectileController”
【发布时间】:2017-11-07 19:49:46
【问题描述】:

这已经被问了大约 100 万次,但我找不到解决问题的方法,反而让我很烦恼。

非常感谢您的帮助,因为我不确定出了什么问题以及如何解决它。

脚本 1:

public class Something : MonoBehaviour {
[SerializeField]
private Rigidbody cannonballInstance;
public ProjectileController projectile;
public Transform firePoint;
[SerializeField]
[Range(10f, 80f)]
private float angle = 45f;
private void Update()
{
 if (Input.GetMouseButtonDown(0))
 {
     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     RaycastHit hitInfo;
     if (Physics.Raycast(ray, out hitInfo))
     {
         FireCannonAtPoint(hitInfo.point);
     }
 }
}
private void FireCannonAtPoint(Vector3 point)
{
 var velocity = BallisticVelocity(point, angle);
 Debug.Log("Firing at " + point + " velocity " + velocity);
 ProjectileController newProjectile = Instantiate(cannonballInstance, transform.position, transform.rotation) as ProjectileController;
 //cannonballInstance.transform.position = transform.position;
 //cannonballInstance.velocity = velocity;
}
private Vector3 BallisticVelocity(Vector3 destination, float angle)
{
 Vector3 dir = destination - transform.position; // get Target Direction
 float height = dir.y; // get height difference
 dir.y = 0; // retain only the horizontal difference
 float dist = dir.magnitude; // get horizontal direction
 float a = angle * Mathf.Deg2Rad; // Convert angle to radians
 dir.y = dist * Mathf.Tan(a); // set dir to the elevation angle.
 dist += height / Mathf.Tan(a); // Correction for small height differences
 // Calculate the velocity magnitude
 float velocity = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
 return velocity * dir.normalized; // Return a normalized vector.
}

在实例化时从 previos 调用以下内容,导致错误是由于我尝试创建的类型还是什么? 脚本 2:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileController : MonoBehaviour {

public float speed;
private Vector3 oldVelocity;
private Rigidbody rigidbodyTemp;
private int bounceLimit = 3;

// Use this for initialization
void Start () {
    rigidbodyTemp = GetComponent<Rigidbody>();
    rigidbodyTemp.isKinematic = false;
    rigidbodyTemp.freezeRotation = true;
    rigidbodyTemp.detectCollisions = true;
}

// Update is called once per frame
void FixedUpdate () {
    rigidbodyTemp.AddForce(transform.forward * speed);
    oldVelocity = rigidbodyTemp.velocity;
}

private void OnCollisionEnter(Collision collision)
{
    bounceLimit -= 1;
    if (collision.gameObject.tag == "Bulllet") // Check if hit another bullet
    {
        Destroy(this.gameObject);
    }
    else if (collision.gameObject.tag == "Crate") // Check if a Crate has been hit, will hold power ups
    {
        Destroy(this.gameObject);
        Destroy(collision.gameObject);
        PickUUpBounce.isActive = true;
    }

    else if (collision.gameObject.tag == "Player") // Check if hit a player
    {
        Destroy(this.gameObject);
    }
    else if (collision.gameObject.tag == "Enemy") // Check if enemy is hit
    {
        Destroy(this.gameObject);
        Destroy(collision.gameObject);
    }

    else if (bounceLimit == 0) // check if bounce limit is reached
    {
        Destroy(this.gameObject);
    }
    else // bounce
    {
        Vector3 reflectedVelocity;
        Quaternion rotation;

        ContactPoint contact = collision.contacts[0]; // stores contact point for reflected velocity

        reflectedVelocity = Vector3.Reflect(oldVelocity, contact.normal); // reflected velocity equals a reflection of the old velocity around the contact point

        rigidbodyTemp.velocity = reflectedVelocity; // Change rigidbody velocity
        rotation = Quaternion.FromToRotation(oldVelocity, reflectedVelocity);  // old directyion -> new direction
        transform.rotation = rotation * transform.rotation; // front face always facing the front

    }

}

}

【问题讨论】:

  • 你至少需要知道错误发生在哪一行。顺便说一句,您的 Bullet 拼写错误(您的有 3 个 L)
  • Instantiate 的签名是什么样的?它是在第一个位置寻找刚体吗?此外,它似乎返回一个刚体,如果是这样,是否有刚体到 ProjectileController 的转换(因为你正试图通过'as'转换它)?它可能不知道如何进行这种转换。
  • @ChrisDunaway 第 49 行,或者该行包含 ' ProjectileController newProjectile = Instantiate(cannonballInstance, transform.position, transform.rotation) as ProjectileController; ' 忽略拼写现在只是一个原型

标签: c# unity3d rigid-bodies


【解决方案1】:

您正在实例化的预制件 (cannonballInstance) 被声明为 Rigidbody。当您调用Instantiate 函数并将cannonballInstance 传递给它时,它将返回Rigidbody 而不是ProjectileController

ProjectileController 是一个脚本。您不能将返回的 Rigidbody 转换为 ProjectileController。您必须使用GetComponent 来检索附加到您的预制件的ProjectileController 实例(cannonballInstance)。

ProjectileController newProjectile = Instantiate(cannonballInstance, transform.position, transform.rotation).GetComponent<ProjectileController>();

最好将那行代码分成几段,以便在任何内容为空的情况下更容易调试。

Rigidbody rg = Instantiate(cannonballInstance, transform.position, transform.rotation);
ProjectileController newProjectile = rg.GetComponent<ProjectileController>();

【讨论】:

    猜你喜欢
    • 2013-07-14
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多