1
\$\begingroup\$

I have a script that will create new GameObjects and will place it where the mouse is placed on the terrain. Now I need to have a check for collision on other already placed GameObjects on the field.

I check different tutorials and documentation and cannot find a way to do this in code.

My code looks like:

objectToPlace = (GameObject)AssetDatabase.LoadAssetAtPath("Assets/Game/3D Models/Buildings/" + objectName + ".fbx", typeof(GameObject));
objectToPlace.SetActive(true);
objectToPlace.transform.localScale = new Vector3(1, 1, 1);
objectToPlace = Instantiate(objectToPlace);

objectToPlace.transform.Rotate(Vector3.right * 90);

BoxCollider collider = (BoxCollider)objectToPlace.AddComponent(typeof(BoxCollider));
collider.isTrigger = true;

In the same class as the above code I have OnTriggerEnter function. But that function is not called. How can I link the Collider to that function in Unity 5.6?

I also tried using the Physics.CheckBox for checking if my new create gameObject does not collide to any other object. But without any succes.

\$\endgroup\$
  • \$\begingroup\$ I didn't confidered using Physics.Checkbox before. Can you give a small example of using that. When I check for collisions using if (!Physics.CheckBox(objectToPlace.GetComponent<BoxCollider>().center, objectToPlace.GetComponent<BoxCollider>().size/2)) I always getting false \$\endgroup\$ – JimmyD Jun 5 '17 at 5:28
  • \$\begingroup\$ For now the default values \$\endgroup\$ – JimmyD Jun 5 '17 at 5:31
  • \$\begingroup\$ When I check also for triggers nothing happend when the two objects collide. Physics.CheckBox(objectToPlace.GetComponent<BoxCollider>().center, objectToPlace.GetComponent<BoxCollider>().size, objectToPlace.transform.rotation, objectToPlace.layer, QueryTriggerInteraction.Collide) \$\endgroup\$ – JimmyD Jun 5 '17 at 5:47
  • \$\begingroup\$ What is the best sollution to fix this? \$\endgroup\$ – JimmyD Jun 5 '17 at 5:55
1
\$\begingroup\$

I created a custom class for the collision detection with the OnTriggerExit, OnTriggerStay and OnTriggerEnter funtions. Also in my class where I place my models I added:

objectToPlace.AddComponent(typeof(BuildingColliderHandler));
\$\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.