1
\$\begingroup\$

I'm making a scanner that scans the "world" (like a 10 x 10 space), and I'm trying to sense a GameObject called pointer.

They both have colliders, they both have triggers, and the scanner has a rigidbody. I have tried the OnTriggerEnter method outside of the update, and it worked, but as soon as I put it inside of Update, it breaks.

I don't have to worry about being specific on what the scanner is detecting, because those two are the only ones with a collider.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scan : MonoBehaviour
{
    public int worldHeight;
    public int worldWidth;    

    public bool sensed;

    public bool spaceBar = false;

    void Update()
    {
        if (Input.GetKeyDown("space") && spaceBar == false)
        {
            spaceBar = true;

            sensed = false;

            //brings scanner to top left corner of world
            transform.position = new Vector3(worldWidth / 2 * -0.64f + 0.32f, worldHeight / 2 * 0.64f + 0.32f, -1);

            for (int sizey = 0; sizey < worldHeight; sizey++)
            {
                if (sensed == false)
                {
                    //shifts scanner down
                    transform.position = new Vector3(worldWidth / 2 * -0.64f - 0.32f, transform.position.y, -1);
                    transform.position = transform.position - new Vector3(0, 0.64f);

                    for (int sizex = 0; sizex < worldWidth; sizex++)
                    {
                        if (sensed == false)
                        {
                            //shifts scanner right
                            transform.position = transform.position + new Vector3(0.64f, 0);

                            void OnCollisionEnter2D(Collision2D grid)
                            {
                                //not working ;-;
                                sensed = true;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            spaceBar = false;
        }
    }
}
\$\endgroup\$
2
\$\begingroup\$

Unity will call your OnTriggerEnter or OnCollisionEnter callback only if it is a member of your type, not a local method buried in another function.

It looks like you might want to use a physics query here instead, like Physics.OverlapBox. This lets you check for overlapping physics objects in a particular volume of space on demand, using layers or trigger query controls to filter what kinds of objects should be detected.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.