Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

c# - Physics2D.Raycast returning null

I have a bit of a issue that has me super stumped here. I am going from Key codes , to mouse input - then it later become touch input, but first I want to figure out why i cant do this with just a mouse.

I have a raycast2d setup - and I want the raycast to read collision with my objects on the screen. They are to only react if its an object tagged as "Cat" - essentially once that happens, the cat will swipe out and try to attack. However, it tells me the tagg itself is a reference that instantiated. But the object itself exists by default so im not sure what to do here. Here is my whole script.

 void Update() {
    //if ((Input.GetKeyDown(KeyCode.O) && !attacking && attackTimer <= 0)) {
    if (Input.GetMouseButtonDown(0) && !attacking && attackTimer <= 0) {  //every frame check to see if the mouse has been clicked.
                                                                          //Get the mouse position on the screen and send a raycast into the game world from that position.
        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);//Vector 2 means only 2 points of axis are read. worldpoint means check the point of the world. Camera is used to determien what we are looking at, and we fill it with our mouse location.
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);
        if (hit.collider == null) {//THIS IS THE LINE that says it is having issues. If i REMOVE this line, ANYWHERE i click on the screen activates the cat and thats not what I want to happen.

            Debug.Log("No Object Touched");

            if (hit.collider.CompareTag("Cat")) {
                GameManager.Instance.AudioSource.PlayOneShot(SoundManager.Instance.Swipe);

                attacking = true;
                attackTimer = attackCd;

                attackTrigger.enabled = true;
            }

UPDATED CODE TO MATCH REQUESTED CHANGES: The error im now getting is the NullreferenceException - for:

 if (hit.collider.CompareTag("Cat")) {

This was the same error i was getting before, after retesting with the methods programmer recommended to test.

The console WILL show me, that I have not clicked a object, then show me the null. So I guess its trying to tell me that it doesnt find anythign tagged as cat that exist in the scene? Even though Cat is a custom tag added, and it was applied to the game object that is the cat - with a Box collider. Does it need a material or anything to read it exists? Is there another way I can call this object on click of its specific location?

UPDATE:

       Debug.Log("No Object Touched");
                if (hit.collider) {
                    if (hit.collider.tag == "cat1") { - 

this got rid of the null reference, BUT It doesnt read the cat at all. if i click the cat nothing happens. and yes it is now tagged as "cat1" properly in editor. meanign tags - new custom tag, created cat1 tag. went to game object, changed tag to cat1. Also ensured a colider is on, with is trigger.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After hours of searching, I finally figured out the reason for getting null.

You need to attach 'New Component' > 'Physics' > 'Box Collider' to your sprite game object.

Now you can use the below code snippet in the script added to your game-object to know if the object is clicked:

private Ray ray;
private RaycastHit hit;

private void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) 
    {
        ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);

        if (Physics.Raycast(ray, out hit, Mathf.Infinity))
        {
            if (hit.transform.gameObject.name == "YourGameObject")
            {
                // Do your stuff on click
            }
        }
    }
}

This is the reason why 3d objects can easily detect touches, because they already have colliders attached to them when you create them.

Hope this answer helps someone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...