无法转换类型 'UnityEngine.Rigidbody' en 'UnityEngine.GameObject 并且没有 Addforce 的定义



我在Unity中的脚本有两个问题,一个是获取刚体,另一个是对球施加一些力。

对于刚体[26,23]无法将类型"UnityEngine.Rigidbody"隐式转换为"UnityEngine.GameObject"[Assembly CSharp]

对于Addforce[52,24]"GameObject"不包含"Addforce"的定义,也找不到接受"GameObject"类型的第一个参数的可访问扩展方法"Addforce"(是否缺少using指令或程序集引用?([assembly CSharp]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StrokeManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}
GameObject playerBallRB;
bool doRoll = false;
private void FindPlayerBall() 
{
GameObject go = GameObject.FindGameObjectWithTag("Player");
if(go == null)
{
Debug.LogError("Ball not found. ");
}
playerBallRB = go.GetComponent<Rigidbody>();
}
// Update is called once per visual frame Input
private void Update() 
{
if(Input.GetKey(KeyCode.Space))  
{
doRoll = true;
}
}
// FixedUpdate runs on every tick of the physics engine, Manipulation
void FixedUpdate()
{
if(doRoll)
{
// Ball roll
doRoll = false;
Vector3 forceVec = new Vector3(0, 0, 10f);
playerBallRB.Addforce(forceVec, ForceMode.Impulse);
} 
}
}

谢谢你的帮助。

确保向游戏对象添加刚体。

至于你的代码,你需要在你的playerBall上附加一个刚体。然后,你需要更改你的代码,让它抓住你的刚体,而不仅仅是你的游戏对象:

playerBallRB.gameObject.rigidbody = go.GetComponent<Rigidbody>();
playerBallRB.gameObject.rigidbody.Addforce(forceVec, ForceMode.Impulse);

相关内容

最新更新