简体   繁体   中英

Accessing a bool from a different script in Unity C#

I have a bool variable ( isGrounded ) from my player's movement control script that I want to access in another GameObject .

BallController.cs

public class BallController : MonoBehaviour {
    Transform myTrans;
    Rigidbody2D myBody;

    public bool isGrounded = true;
    public bool release = false;
}

GravityPull.cs

public class GravityPull : MonoBehaviour {

    public GameObject target;
    public int moveSpeed;
    public int maxdistance;
    private float distance;


    void Start ()
    {
        target= (GameObject.Find("Ball (1)"));
    }


    void Update ()
    {
        distance = Vector2.Distance (target.transform.position, transform.position);

        if (distance < maxdistance && target.isGrounded)
        {
             target.transform.position = Vector2.MoveTowards(target.transform.position, transform.position, moveSpeed * Time.deltaTime / distance);
        }
    }
}

If I make my target a GameObject than I can find it using .find . But if I do this I can't access the bool. If I make my target a BallController then I can access the bool, but I can't use .find to find the class. I also can't cast the GameObject as a BallController . Can someone tell me what I'm doing wrong here?

target.getComponent<BallController>().isGrounded

这应该足够了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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