- Home /
How to prevent an object from instantiating inside another object?
So I have a sphere game object that I want to instantiate. I've been able to get it so that when you click on a sphere or its clone that another instantiation doesn't occur. However, when I click right next to the sphere, another sphere is created that meshes with the other. Here's my code and see if you can try to help me:
using UnityEngine;
using System.Collections;
public class Instantiate : MonoBehaviour {
Ray ray;
RaycastHit hit;
public GameObject Sphere;
public int count;
public Transform teleport1;
public Transform teleport2;
public GameObject Cube;
void OnTriggerEnter(Collider other) //This is where I've tried to stop the meshing, but to no avail.
{
if(other.gameObject.CompareTag ("Sphere"))
{
other.gameObject.Destroy;
}
}
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
Cube.transform.position = teleport1.position;
}
if(Input.GetButtonDown("Fire2"))
{
Cube.transform.position = teleport2.position;
}
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit))
{
if (Input.GetMouseButtonDown (0))
{
if(hit.transform.name != "Sphere" && hit.transform.name != "Sphere(Clone)")
{
Instantiate (Sphere, hit.point + new Vector3(0, 0.5f, 0), Quaternion.identity);
count = count + 1;
}
}
}
}
}
Answer by Bieere · Oct 08, 2015 at 05:05 PM
A quick fix would be to store your instantiated objects in a List, and just check the distance from world position to the nearest spheres. if the position is within the radius*2 (Diameter ) of the instantiating sphere, return null/don't spawn your sphere.
Also the reason your OnTriggerEnter is likely not working is that there needs to be both a collider and rigidbody for it to work. You wont need it any longer after the fix, but you should've used OnColliderEnter(), though it would be called twice in your case, and caused you some issues i believe.
Your answer
Follow this Question
Related Questions
Need help with dialogue system script 0 Answers
Is there a reason why Unity would be able to read one variable in a script and not another? 1 Answer
After exporting my project from my PC to my laptop the physics of my game work differently. 1 Answer
Left side panel in monodevelop 1 Answer
Script problem 1 Answer