如何将Force添加到另一个脚本的GetComponent<Rigidbody2D>()

问题描述 投票:0回答:1

我正在尝试制作一款类似水果忍者的游戏。但是当我制作水果产卵然后在屏幕上移动的脚本时,我遇到了麻烦。

public class PeaScript : MonoBehaviour
{
    public Rigidbody2D peaRB;
    // Start is called before the first frame update
    void Start()
    {
        peaRB = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void MovePea()
    {
       peaRB.AddForce(Vector2.right * 3, ForceMode2D.Impulse);
    }
}

public class Fruit_Spawn : MonoBehaviour
{
    public GameObject FruitOne;
    public GameObject FruitTwo;
    public GameObject FruitThree;
    public GameObject FruitFour;
    bool one = false;
    bool two = false;
    bool three = false;
    bool four = false;
    float oneF = 0f;
    float twoF = 0f;
    float threeF = 0f;
    float fourF = 0f;
    public int RoundCount = 0;
    private PeaScript PeaScript;
    public Rigidbody2D pea;
    // Start is called before the first frame update
    void Start()
    {
        NewRound();
        FruitOne = GameObject.Find("Pea_vegtable(1)");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    void NewRound()
    {
        oneF = Random.Range(0,2);
        twoF = Random.Range(0, 2);
        threeF = Random.Range(0, 2);
        fourF = Random.Range(0, 2);
        Debug.Log(oneF);
        if (RoundCount !=5 && oneF==1)
        {
            PeaScript = FindObjectOfType<PeaScript>();
            PeaScript.peaRB = pea;
            transform.position = new Vector3(1, 1, 0);
            pea.AddForce(Vector2.right * 3, ForceMode2D.Impulse);

        }
    }
}

我尝试只在豌豆脚本中创建一个函数来运行该函数来推动它,但这不起作用,因为它不允许我调用它。

c# unity-game-engine
1个回答
0
投票

你为什么要使用hard方式?将公共变量设置为 PeaScript 并将您的脚本(在这种情况下您需要添加具有此脚本的游戏对象)从右侧的组件添加到您的游戏对象,然后您可以访问您的脚本或者您可以使用

GameObject peaObject = GameObject.Find("YOUR_PEA_OBJECT_NAME");
PeaScript script = peaObject.GetComponent<PeaScript>();

© www.soinside.com 2019 - 2024. All rights reserved.