简体   繁体   中英

Raycast hit error

I have a question, when I write this to play a sound when the player is under the distance from 4 unity meter and press "e", but it gives me an error that hit can't convert to float . What should I do now?

public AudioSource sound;

public int rayLength = 4;
public GameObject doorText;
RaycastHit hit;

void Update()
{
    var fwd = transform.TransformDirection(Vector3.forward);

    if (Physics.Raycast(transform.position, fwd, hit, rayLength))
    {
        if (hit.collider.gameObject.tag == "Boxen")
        {
            doorText.gameObject.SetActive(true);
            if (Input.GetKeyDown("e")) //or Input.GetKeyDown("e")    Input.GetButtonDown("Fire1")
            {
                sound.Play();
            }
        }
    }

    else
    {
        doorText.gameObject.SetActive(false);
    }
}

You are missing an out keyword on that call

if (Physics.Raycast(transform.position, fwd, out hit, rayLength)) {

It allows the method to write into the hit argument. Without it C# will not recognize the desired overload and point you to the closest available one, in this case, where the third argument is a float.

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