简体   繁体   中英

Getting Errors with Raycasts2D Unity C#

I am working on a project that uses raycasts as part of the shooting mechanic. For some reason though I am getting errors when using ray casts and I am not sure how to fix them. Here's my code:

void Shoot(){
    RaycastHit2D hit;

    if (Physics2D.Raycast(player.position, player.forward, out hit, weapon.range, targetMask)) {
        Debug.Log ("You Hit: " + hit.collider.name);
    }
}

The errors I am getting are:

Assets/Scripts/Shooting.cs(26,17): error CS1502: The best overloaded method match for `UnityEngine.Physics2D.Raycast(UnityEngine.Vector2, UnityEngine.Vector2, float, int, float)' has some invalid arguments

And

Assets/Scripts/Shooting.cs(26,62): error CS1615: Argument '#3' does not require 'out' modifier. Consider removing `out' modifier

Thank you for any suggestions why this may be...

The Unity documentation for 2D Raycasts can be unclear about what you can use. Here's all of the available methods:

Raycast(Vector2 origin, Vector2 direction) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth) : RaycastHit2D

Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth) : RaycastHit2D

Unlike 3D raycasts, none of the available overloads use the out modifier.

(In short you're using a method that doesn't exist, and it's specifically complaining about out hit )

They all return a RaycastHit2D struct . This means that you can't compare it to null to see if the hit worked. So, based on the names of your variables, I would assume you meant this:

void Shoot(){
    RaycastHit2D hit;

    hit = Physics2D.Raycast(player.position, player.forward, weapon.range, targetMask);

    // As suggested by the documentation, 
    // test collider (because hit is a struct and can't ever be null):
    if(hit.collider != null){
        Debug.Log ("You Hit: " + hit.collider.name);
    }
}

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