Need help with Collision Detection

There are two objects one is a sphere another is an invisible wall. The moving sphere is supposed to collide with the invisible wall, and stop moving (from it’s go variable being set to false). Each object has a script attached to them. Here are those scripts:

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

public class sphereScript : MonoBehaviour
{
    public bool go = true;
    Vector3 movement = new Vector3(0f, 0f, -1f);
    // Start is called before the first frame update
    void Start()
    {
        go = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (go)
        {
            transform.position += movement * Time.deltaTime * 4;
            transform.eulerAngles += movement;
        }
    }
    public void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "Cube2")
        {
            //go = false;
            Debug.Log("hit ");
        }

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

public class invisibleBox2 : MonoBehaviour
{

    public GameObject sphere;
    sphereScript sphereScript2;

    // Start is called before the first frame update
    void Start()
    {
        gameObject.GetComponent<Renderer>().enabled = false;

        sphere = GameObject.Find("Sphere");
        sphereScript2 = sphere.GetComponent<sphereScript>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "Sphere")
        {
            //sphereScript2.go = false;
           
            Debug.Log("hit ");
        }
    }
}


Make sure you are meeting the requirements to be called. See docs.

Also put a Debug.Log() just inside this and print the name of anything you’re hitting.

This will cause Rigidbody collisions to be missed. You DO have a Rigidbody on here, right? It’s required to get collisions.

When moving stuff yourself and there is physics involved, always use .MovePosition() on the Rigidbody instance.

1 Like

thank you very much