- Home /
Get all surrounding gameObjects
I have a 8 x 8 sets of cube as so:
for (var x = 0; x < 8; x++){
for (var y = 0; y < 8; y++){
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = Vector3(x, y, 0);
}
}
When OnMouseDown on a cube I would like to get the set of surrounding cubes.
For example, if I click the blue cube, I want to get the all of the yellow cubes. Also is there a function to expand radius? For example, I want to include sets of red cubes with the yellow cubes.
For me, I'd put all game objects in a 2D array and use the array to find the cubes I want to select. If you don't want to use an array, you could use Physics.OverlapSphere(). For the 'position' parameter use the position of the blue cube. For radius, use a value somewhat larger than 1/2 of the face diagonal of the cube.
@robertbu Even if I put all the game objects in a 2D array, how would you go about getting the surrounding cubes giving only the On$$anonymous$$ouseDown event? Physics.OverlapSphere() would seem easier, but I'm concerned about performance. I'm curious about the 2D approach.
Answer by BimSekai · Jul 24, 2013 at 02:34 PM
I'm not so good at javascript, but I can give you the equivalent in C#:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GridCube{
public static List<GridCube> AllCubes = new List<GridCube>();
private int x;
private int y;
private GameObject cube;
// Use this for initialization
void Start () {
AllCubes.Add(this);
}
public bool HasPosition(int aX, int aY)
{
return (x == aX && y == aY);
}
public void Place(int aX, int aY)
{
if (cube != null)
{
GameObject.Destroy(cube);
}
x = aX;
y = aY;
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
public int GetSpacesTo(GridCube targetCube)
{
int ySpaces = Mathf.Abs(this.y - targetCube.y);
int xSpaces = Mathf.Abs(this.x - targetCube.x);
return xSpaces + ySpaces;
}
public static GridCube GetCubeOfCoords(int aX, int aY)
{
foreach (GridCube gridcube in AllCubes)
{
if (gridcube.HasPosition(aX, aY))
{
return gridcube;
}
}
return null;
}
public static List<GridCube> GetCubesAround(GridCube centerCube , int nbCases)
{
List<GridCube> cubesAround = new List<GridCube>();
foreach (GridCube gridCube in AllCubes)
{
if (centerCube.GetSpacesTo(gridCube) == nbCases)
{
DoSomethingToThatCube();
}
}
}
}
This is very far from being optimised but it will do the work =) Does it suit you ?
Your answer
Follow this Question
Related Questions
Sphercast hitinfo TextureCoord rounded? 1 Answer
anyone know the maths to take into account Bounciness when calculating trajectories? 1 Answer
Why is my spherecast returning an incorrect hit on mesh collider? 1 Answer
Physics.SphereCastAll - how far did the trace travel? 3 Answers
How can the resultant velocity of an object after a potential collision be predicted? 1 Answer