Search code examples
c#unity-game-enginecollision-detectioncollider

Detect Collision for an instantly refreshed object


so i have an old code for a "Connect4" game it was written years ago, now i am having a big problem getting it results and rebuild them for a unity3D project.

the problem is that every gameObject (i've managed to instanciate in the scene) is, meant to be destroyed and reinstantiated every frame (and i have the feeling that is really more that a frame time); wanting to get the color of each gameobject in time seem to be really challenging, i am supposed now to not enter the code created i am only supposed to get the information from what i get as graphical results.

so now i have a board of boxes having a grid disposition that changes colors according to the player turns (red for the cp and yellow for the plyer).

i created a fixed boxes having colliders and wanted to get the game objects colliding with it everyframe but i failed .

PS: i tested this code and every solution i found in this community hope to find somehelp, thank you.

using UnityEngine;
using System.Collections;

public class SelectorCode : MonoBehaviour
{
    public Collision other;

    public GameObject GO;

    void OnTriggerEnter(Collider other)
    {
        GO = other.gameObject;


    }
    void OnTriggerStay(Collider other)
    {
        GO = other.gameObject;


    }
    void OnTriggerExit(Collider other)
    {
        GO = other.gameObject;


    }

    void Update()
    {

        GO = this.other.gameObject;

    }
}

Solution

  • First make sure the object to which the SelectorCode component is attached has a trigger collider (property "Is Trigger" is checked).

    Next you'll get an error in the Updatemethod with GO = this.other.gameObject; since other is never assigned. I think you should remove that line.

    Finally, in OnTriggerExit you put in GO the object that is leaving your collider, that doesn't make sense, you should probably assign GO to null at this point :

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject == GO) 
        {
            GO = null;
        }
    }