简体   繁体   English

GameObject' 不包含 'AddForce' 的定义 || Unity3D

[英]GameObject' does not contain a definition for 'AddForce' || Unity3D

I have an error:我有一个错误:

'GameObject' does not contain a definition for 'AddForce' and no accessible extension method
'AddForce' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)

Code:代码:

public float power = 500.0f;
GameObject var;

void OnCollisionEnter(Collision myCollision) {
if (myCollision.gameObject.name == "Cube") {
    var = GameObject.Find("Cube");
    var.AddForce(new Vector3(0.0f, 0.0f, power));
  }
}

I want change coords of current object, in a collision with other objects.我想在与其他对象发生碰撞时更改当前 object 的坐标。

From what you are trying to, I am assuming that you are trying to add a force to the object that it has collided with.根据您的尝试,我假设您正在尝试向与它相撞的 object 施加力。

First of all, you did:首先,你做了:

if (myCollision.gameObject.name == "Cube")
  {
    var = GameObject.Find("Cube");
    var.AddForce(new Vector3(0.0f, 0.0f, power));
  }

Try to avoid GameObject.Find(string) method, as it is an expensive call.尽量避免使用GameObject.Find(string)方法,因为它是一个昂贵的调用。
In fact, you don't even need to do that, since you actually have the game object you are colliding with already, that is what the myCollision for.事实上,您甚至不需要这样做,因为您实际上已经拥有正在碰撞的游戏 object,这就是myCollision的用途。

You can do this instead:你可以这样做:

if (myCollision.gameObject.name == "Cube")
  {
    var = myCollision.gameObject; // Aka the gameobject you have collided with.
    var.AddForce(new Vector3(0.0f, 0.0f, power));
  }

Going back to the question , what you were trying to do is to add force to a rigidbody, but however var is of type GameObject , not RigidBody .回到问题,你试图做的是向刚体添加力,但是varGameObject类型,而不是RigidBody

What you need to do is to get the component of the RigidBody from the GameObject , like so:您需要做的是从GameObject中获取RigidBody的组件,如下所示:

var.GetComponent<Rigidbody>().AddForce(...

Note that a null reference exception occurs if the GameObject does not have a Rigidbody component attached to it.请注意,如果游戏对象没有附加刚体组件,则会发生 null 引用异常。
Make sure the cube you are colliding with has a RigidBody component in the Unity's Inspector.确保你正在碰撞的立方体在 Unity 的 Inspector 中有一个 RigidBody 组件。

Also, you might want to note that repeated GetComponent() calls can be expensive.此外,您可能需要注意重复GetComponent()调用可能会很昂贵。 You can consider caching it if possible.如果可能,您可以考虑缓存它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM