Unity3D Instantiation Methods

Here is a number of well tested methods/functions I created from my past projects. I kept them in my personal ‘library’ where I store frequently used scripts. I suppose artists and coders have personal working styles and preferences. It helps that they are already written in the style I preferred since I was the one who wrote them. When sharing our codes with others, do keep them clean and easily comprehensible.

Generating Random Position with Vector3:

private Vector3 GetRandomVector3()
{
float randomX = Random.Range(minXContainer, maxXContainer);
float randomY = Random.Range(minYContainer, maxYContainer);

Vector3 v3 = new Vector3(randomX, randomY, fixedY);

return v3;
}

Method Explained: In GetRandomVector3() method above, minXContainer, maxXContainer, minYContainer, maxYContainer capture the highest and lowest values of the x,y coordinates that represent the area of the container (in the example here, the container is a 2D panel). When the method is called, it returned a Vector3 point, a local position inside the container. z value is predetermined and fixed unlike x and y, as the example is based on a 2D panel.

Instantiate & Return A Spawned Object with Random Local Position

[Header("Game Elements")]
public List prefabs;
public GameObject parentContainer;

GameObject spawnItem;
private GameObject SpawnObjects()
{
int selectedElement = Random.Range(0, prefabs.Count);
spawnItem = Instantiate(prefabs[selectedElement], parentContainer.transform) as GameObject;
spawnItem.transform.localPosition = GetRandomVector3();
return spawnItem;
}

Unity3D Public Variables in Inspector View

Method Explained: Public variables are the script component’s parameters/properties in the Unity inspector. In this example, the public <List> that holds the prefabs takes 3 objects (sprites in Red, Green, Blue) through the Inspector. The SpawnObjects() methods did a random selection of a prefab from this <List>, clone the item in the parent container (panel) and set the local position with a Vector 3 value generated via a call made to GetRandomVector3() function.

Overlapping and Intersecting Colliders:

Spawned Loop Count in Unity3D 
public void MatchSpawnObjects()
    {
        for (int j = 0; j < spawned.Count; j++)
        {
            GameObject a = spawned[j];
            Vector3 aV3 = a.transform.localPosition;
            CircleCollider2D C1 = a.GetComponent();

            for (int z = 0; z < j; z++)
            {
                GameObject b = spawned[z];
                Vector3 bV3 = b.transform.localPosition;

                CircleCollider2D C2 = b.GetComponent();

Collider Component Unity3D   Circle Collider 2D Bounding Box in Unity3D

                if (C1.bounds.Intersects(C2.bounds))
                {

                    if(aV3 != bV3)
                    {

                        if (!spawnedTemp.Contains(a)) 
                        {
                            spawnedTemp.Add(a);
                            Destroy(a);
                        }

                        if (!spawnedTemp.Contains(b))
                        {
                            spawnedTemp.Add(b);
                            Destroy(b);
                        }
                        
                    }
                    
                    
                }
               
            }
            
        }
   }

Method Explained: MatchSpawnObjects(), is activated on a pre-generated <List> of instantiated objects called ‘spawned’. We use an outer loop and a nested inner loop to counter checked the items on the list against each other through their indices (index j, z).  In the Unity Inspector, we have set a target of 100 spawned items with 100 iterations applied on the nested loop. The reasons are explained in the previous article. The detection is done via the bounding box property of the collider component. In this case it is a Circle Collider 2D but it could be a box or mesh collider, the choice depends on the shape of the object and how snugly it fits. The size of the circle collider is determined by its radius unit. Within the inner loop, the collided objects are added to a temporary <List> ‘spawnedTemp’ and removed after. I have included this temporary <List> for analysis. It is not required for the purpose stated here.

The methods described in this article are applied in this WebGL application:

Leave a Reply

Your email address will not be published. Required fields are marked *