How to check if there is a collider(gameobject) on the position or not

3.1k views Asked by At

I have a tic tac toe game , and I want to make it dynamical, so I need some collider checking function or method, but I cannot find it in internet, so I am asking here. unity

I have this code for making my tic tac toe dynamic , it is not finished yet.

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

public class Test : MonoBehaviour {

public Transform Button;
public int rows;
public int columns;

void Start () {

    int i = 0;
    int x = 0;
    int y = 0;

    for (i = 0; i < columns; i++) {

        Transform newButton = Instantiate<Transform> (Button);
        newButton.SetParent(GameObject.Find ("ButtonsContainer").transform);
        newButton.localScale = Vector3.one;
        newButton.localPosition = new Vector3(x,y,0);


        }
    }
}
2

There are 2 answers

0
Matthew Loveday On

There are many ways that you determine if a collider is in a certain position, one would be to have a seperate collider object that you move to the position and then do the collision checking on that object using OnCollisionEnter.

While you can achieve your goal this way, I would recommend that you take a different approach to determine where the colliders are. if this is tic tac toe then it's based on a grid, you could store all of the games data within a 2D array and then you would always know the position of the objects without having to scan the scene for them. Not only would this be more efficient but it would also make dealing with the rule checking much easier.

0
cortvi On

The easiest way to detect colliders by code is to use Physics.SphereCast method.